diff --git a/fine-jedis/README.md b/fine-jedis/README.md deleted file mode 100644 index 6d3107627..000000000 --- a/fine-jedis/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# fine-jedis - -版本为3.6.0,内置的apache-commons-pool版本为2.9.0 \ No newline at end of file diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/BaseKeyedPooledObjectFactory.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/BaseKeyedPooledObjectFactory.java index 9a6982897..bfb90e1ab 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/BaseKeyedPooledObjectFactory.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/BaseKeyedPooledObjectFactory.java @@ -17,13 +17,11 @@ package com.fr.third.org.apache.commons.pool2; /** - * A base implementation of {@code KeyedPooledObjectFactory}. + * A base implementation of KeyedPooledObjectFactory. *

* All operations defined here are essentially no-op's. *

- *

* This class is immutable, and therefore thread-safe. - *

* * @see KeyedPooledObjectFactory * @@ -32,8 +30,8 @@ package com.fr.third.org.apache.commons.pool2; * * @since 2.0 */ -public abstract class BaseKeyedPooledObjectFactory extends BaseObject - implements KeyedPooledObjectFactory { +public abstract class BaseKeyedPooledObjectFactory extends BaseObject + implements KeyedPooledObjectFactory { /** * Create an instance that can be served by the pool. @@ -66,7 +64,6 @@ public abstract class BaseKeyedPooledObjectFactory extends BaseObject * Destroy an instance no longer needed by the pool. *

* The default implementation is a no-op. - *

* * @param key the key used when selecting the instance * @param p a {@code PooledObject} wrapping the instance to be destroyed @@ -81,11 +78,10 @@ public abstract class BaseKeyedPooledObjectFactory extends BaseObject * Ensures that the instance is safe to be returned by the pool. *

* The default implementation always returns {@code true}. - *

* * @param key the key used when selecting the object * @param p a {@code PooledObject} wrapping the instance to be validated - * @return always {@code true} in the default implementation + * @return always true in the default implementation */ @Override public boolean validateObject(final K key, final PooledObject p) { @@ -96,7 +92,6 @@ public abstract class BaseKeyedPooledObjectFactory extends BaseObject * Reinitialize an instance to be returned by the pool. *

* The default implementation is a no-op. - *

* * @param key the key used when selecting the object * @param p a {@code PooledObject} wrapping the instance to be activated @@ -111,7 +106,6 @@ public abstract class BaseKeyedPooledObjectFactory extends BaseObject * Uninitialize an instance to be returned to the idle object pool. *

* The default implementation is a no-op. - *

* * @param key the key used when selecting the object * @param p a {@code PooledObject} wrapping the instance to be passivated diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/BaseObjectPool.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/BaseObjectPool.java index f3cfe6a77..47b567f58 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/BaseObjectPool.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/BaseObjectPool.java @@ -22,7 +22,6 @@ package com.fr.third.org.apache.commons.pool2; * indicating it is unsupported or throw {@link UnsupportedOperationException}. *

* This class is intended to be thread-safe. - *

* * @param Type of element pooled in this pool. * @@ -85,9 +84,8 @@ public abstract class BaseObjectPool extends BaseObject implements ObjectPool /** * {@inheritDoc} *

- * This affects the behavior of {@code isClosed} and - * {@code assertOpen}. - *

+ * This affects the behavior of isClosed and + * assertOpen. */ @Override public void close() { @@ -97,14 +95,14 @@ public abstract class BaseObjectPool extends BaseObject implements ObjectPool /** * Has this pool instance been closed. * - * @return {@code true} when this pool has been closed. + * @return true when this pool has been closed. */ public final boolean isClosed() { return closed; } /** - * Throws an {@code IllegalStateException} when this pool has been + * Throws an IllegalStateException when this pool has been * closed. * * @throws IllegalStateException when this pool has been closed. diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/BasePooledObjectFactory.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/BasePooledObjectFactory.java index 2be3e35fd..dad5bb0bb 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/BasePooledObjectFactory.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/BasePooledObjectFactory.java @@ -17,7 +17,7 @@ package com.fr.third.org.apache.commons.pool2; /** - * A base implementation of {@code PoolableObjectFactory}. + * A base implementation of PoolableObjectFactory. *

* All operations defined here are essentially no-op's. *

diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/DestroyMode.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/DestroyMode.java deleted file mode 100644 index 30c2a5303..000000000 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/DestroyMode.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.fr.third.org.apache.commons.pool2; - -/** - * Destroy context provided to object factories via destroyObject methods. Values provide information about why the pool - * is asking for a pooled object to be destroyed. - * - * @since 2.9.0 - */ -public enum DestroyMode { - /** Normal destroy */ - NORMAL, - /** Destroy abandoned object */ - ABANDONED -} diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/KeyedObjectPool.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/KeyedObjectPool.java index ae2cc698f..c21c1844a 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/KeyedObjectPool.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/KeyedObjectPool.java @@ -17,18 +17,14 @@ package com.fr.third.org.apache.commons.pool2; import java.io.Closeable; -import java.util.Collection; -import java.util.Iterator; import java.util.NoSuchElementException; /** * A "keyed" pooling interface. *

* A keyed pool maintains a pool of instances for each key value. - *

*

* Example of use: - *

*
 Object obj = null;
  * Object key = "Key";
@@ -52,93 +48,22 @@ import java.util.NoSuchElementException;
  * one instance per key value, or may choose to maintain a pool of instances
  * for each key (essentially creating a {@link java.util.Map Map} of
  * {@link ObjectPool pools}).
- * 

*

- * See {@link com.fr.third.org.apache.commons.pool2.impl.GenericKeyedObjectPool + * See {@link org.apache.commons.pool2.impl.GenericKeyedObjectPool * GenericKeyedObjectPool} for an implementation. - *

* * @param The type of keys maintained by this pool. * @param Type of element pooled in this pool. * * @see KeyedPooledObjectFactory * @see ObjectPool - * @see com.fr.third.org.apache.commons.pool2.impl.GenericKeyedObjectPool GenericKeyedObjectPool + * @see org.apache.commons.pool2.impl.GenericKeyedObjectPool GenericKeyedObjectPool * * @since 2.0 */ -public interface KeyedObjectPool extends Closeable { - - /** - * Create an object using the {@link KeyedPooledObjectFactory factory} or - * other implementation dependent mechanism, passivate it, and then place it - * in the idle object pool. {@code addObject} is useful for - * "pre-loading" a pool with idle objects (Optional operation). - * - * @param key the key a new instance should be added to - * - * @throws Exception - * when {@link KeyedPooledObjectFactory#makeObject} fails. - * @throws IllegalStateException - * after {@link #close} has been called on this pool. - * @throws UnsupportedOperationException - * when this pool cannot add new idle objects. - */ - void addObject(K key) throws Exception, IllegalStateException, - UnsupportedOperationException; - - /** - * Calls {@link KeyedObjectPool#addObject(Object)} with each - * key in {@code keys} for {@code count} number of times. This has - * the same effect as calling {@link #addObjects(Object, int)} - * for each key in the {@code keys} collection. - * - * @param keys - * {@link Collection} of keys to add objects for. - * @param count - * the number of idle objects to add for each {@code key}. - * @throws Exception - * when {@link KeyedObjectPool#addObject(Object)} fails. - * @throws IllegalArgumentException - * when {@code keyedPool}, {@code keys}, or any value - * in {@code keys} is {@code null}. - * @see #addObjects(Object, int) - */ - default void addObjects(final Collection keys, final int count) throws Exception, IllegalArgumentException { - if (keys == null) { - throw new IllegalArgumentException(PoolUtils.MSG_NULL_KEYS); - } - final Iterator iter = keys.iterator(); - while (iter.hasNext()) { - addObjects(iter.next(), count); - } - } - +public interface KeyedObjectPool extends Closeable { /** - * Calls {@link KeyedObjectPool#addObject(Object)} - * {@code key} {@code count} number of times. - * - * @param key - * the key to add objects for. - * @param count - * the number of idle objects to add for {@code key}. - * @throws Exception - * when {@link KeyedObjectPool#addObject(Object)} fails. - * @throws IllegalArgumentException - * when {@code key} is {@code null}. - * @since 2.8.0 - */ - default void addObjects(final K key, final int count) throws Exception, IllegalArgumentException { - if (key == null) { - throw new IllegalArgumentException(PoolUtils.MSG_NULL_KEY); - } - for (int i = 0; i < count; i++) { - addObject(key); - } - } - - /** - * Obtains an instance from this pool for the specified {@code key}. + * Obtains an instance from this pool for the specified key. *

* Instances returned from this method will have been either newly created * with {@link KeyedPooledObjectFactory#makeObject makeObject} or will be @@ -146,19 +71,16 @@ public interface KeyedObjectPool extends Closeable { * {@link KeyedPooledObjectFactory#activateObject activateObject} and then * (optionally) validated with * {@link KeyedPooledObjectFactory#validateObject validateObject}. - *

*

* By contract, clients must return the borrowed object * using {@link #returnObject returnObject}, * {@link #invalidateObject invalidateObject}, or a related method as - * defined in an implementation or sub-interface, using a {@code key} + * defined in an implementation or sub-interface, using a key * that is {@link Object#equals equivalent} to the one used to borrow the * instance in the first place. - *

*

- * The behavior of this method when the pool has been exhausted is not + * The behaviour of this method when the pool has been exhausted is not * strictly specified (although it may be specified by implementations). - *

* * @param key the key used to obtain the object * @@ -176,146 +98,133 @@ public interface KeyedObjectPool extends Closeable { V borrowObject(K key) throws Exception, NoSuchElementException, IllegalStateException; /** - * Clears the pool, removing all pooled instances (optional operation). + * Return an instance to the pool. By contract, obj + * must have been obtained using + * {@link #borrowObject borrowObject} or a related method as defined in an + * implementation or sub-interface using a key that is + * equivalent to the one used to borrow the instance in the first place. * - * @throws UnsupportedOperationException when this implementation doesn't - * support the operation + * @param key the key used to obtain the object + * @param obj a {@link #borrowObject borrowed} instance to be returned. * - * @throws Exception if the pool cannot be cleared + * @throws IllegalStateException + * if an attempt is made to return an object to the pool that + * is in any state other than allocated (i.e. borrowed). + * Attempting to return an object more than once or attempting + * to return an object that was never borrowed from the pool + * will trigger this exception. + * + * @throws Exception if an instance cannot be returned to the pool */ - void clear() throws Exception, UnsupportedOperationException; + void returnObject(K key, V obj) throws Exception; /** - * Clears the specified pool, removing all pooled instances corresponding to - * the given {@code key} (optional operation). - * - * @param key the key to clear + * Invalidates an object from the pool. + *

+ * By contract, obj must have been obtained + * using {@link #borrowObject borrowObject} or a related method as defined + * in an implementation or sub-interface using a key that is + * equivalent to the one used to borrow the Object in the first + * place. + *

+ * This method should be used when an object that has been borrowed is + * determined (due to an exception or other problem) to be invalid. * - * @throws UnsupportedOperationException when this implementation doesn't - * support the operation + * @param key the key used to obtain the object + * @param obj a {@link #borrowObject borrowed} instance to be returned. * - * @throws Exception if the key cannot be cleared + * @throws Exception if the instance cannot be invalidated */ - void clear(K key) throws Exception, UnsupportedOperationException; + void invalidateObject(K key, V obj) throws Exception; /** - * Close this pool, and free any resources associated with it. - *

- * Calling {@link #addObject addObject} or - * {@link #borrowObject borrowObject} after invoking this method on a pool - * will cause them to throw an {@link IllegalStateException}. - *

- *

- * Implementations should silently fail if not all resources can be freed. - *

+ * Create an object using the {@link KeyedPooledObjectFactory factory} or + * other implementation dependent mechanism, passivate it, and then place it + * in the idle object pool. addObject is useful for + * "pre-loading" a pool with idle objects (Optional operation). + * + * @param key the key a new instance should be added to + * + * @throws Exception + * when {@link KeyedPooledObjectFactory#makeObject} fails. + * @throws IllegalStateException + * after {@link #close} has been called on this pool. + * @throws UnsupportedOperationException + * when this pool cannot add new idle objects. */ - @Override - void close(); + void addObject(K key) throws Exception, IllegalStateException, + UnsupportedOperationException; /** - * Returns the total number of instances currently borrowed from this pool but - * not yet returned. Returns a negative value if this information is not - * available. - * @return the total number of instances currently borrowed from this pool but - * not yet returned. + * Returns the number of instances corresponding to the given + * key currently idle in this pool. Returns a negative value if + * this information is not available. + * + * @param key the key to query + * @return the number of instances corresponding to the given + * key currently idle in this pool. */ - int getNumActive(); + int getNumIdle(K key); /** * Returns the number of instances currently borrowed from but not yet - * returned to the pool corresponding to the given {@code key}. + * returned to the pool corresponding to the given key. * Returns a negative value if this information is not available. * * @param key the key to query * @return the number of instances currently borrowed from but not yet - * returned to the pool corresponding to the given {@code key}. - */ + * returned to the pool corresponding to the given key. += */ int getNumActive(K key); /** * Returns the total number of instances currently idle in this pool. * Returns a negative value if this information is not available. * @return the total number of instances currently idle in this pool. - */ + = */ int getNumIdle(); /** - * Returns the number of instances corresponding to the given - * {@code key} currently idle in this pool. Returns a negative value if - * this information is not available. - * - * @param key the key to query - * @return the number of instances corresponding to the given - * {@code key} currently idle in this pool. + * Returns the total number of instances current borrowed from this pool but + * not yet returned. Returns a negative value if this information is not + * available. + * @return the total number of instances current borrowed from this pool but + * not yet returned. */ - int getNumIdle(K key); + int getNumActive(); /** - * Invalidates an object from the pool. - *

- * By contract, {@code obj} must have been obtained - * using {@link #borrowObject borrowObject} or a related method as defined - * in an implementation or sub-interface using a {@code key} that is - * equivalent to the one used to borrow the {@code Object} in the first - * place. - *

- *

- * This method should be used when an object that has been borrowed is - * determined (due to an exception or other problem) to be invalid. - *

+ * Clears the pool, removing all pooled instances (optional operation). * - * @param key the key used to obtain the object - * @param obj a {@link #borrowObject borrowed} instance to be returned. + * @throws UnsupportedOperationException when this implementation doesn't + * support the operation * - * @throws Exception if the instance cannot be invalidated + * @throws Exception if the pool cannot be cleared */ - void invalidateObject(K key, V obj) throws Exception; - + void clear() throws Exception, UnsupportedOperationException; /** - * Invalidates an object from the pool, using the provided - * {@link DestroyMode}. - *

- * By contract, {@code obj} must have been obtained - * using {@link #borrowObject borrowObject} or a related method as defined - * in an implementation or sub-interface using a {@code key} that is - * equivalent to the one used to borrow the {@code Object} in the first - * place. - *

- *

- * This method should be used when an object that has been borrowed is - * determined (due to an exception or other problem) to be invalid. - *

+ * Clears the specified pool, removing all pooled instances corresponding to + * the given key (optional operation). * - * @param key the key used to obtain the object - * @param obj a {@link #borrowObject borrowed} instance to be returned. - * @param mode destroy activation context provided to the factory + * @param key the key to clear * - * @throws Exception if the instance cannot be invalidated - * @since 2.9.0 + * @throws UnsupportedOperationException when this implementation doesn't + * support the operation + * + * @throws Exception if the key cannot be cleared */ - default void invalidateObject(final K key, final V obj, final DestroyMode mode) throws Exception { - invalidateObject(key, obj); - } + void clear(K key) throws Exception, UnsupportedOperationException; /** - * Return an instance to the pool. By contract, {@code obj} - * must have been obtained using - * {@link #borrowObject borrowObject} or a related method as defined in an - * implementation or sub-interface using a {@code key} that is - * equivalent to the one used to borrow the instance in the first place. - * - * @param key the key used to obtain the object - * @param obj a {@link #borrowObject borrowed} instance to be returned. - * - * @throws IllegalStateException - * if an attempt is made to return an object to the pool that - * is in any state other than allocated (i.e. borrowed). - * Attempting to return an object more than once or attempting - * to return an object that was never borrowed from the pool - * will trigger this exception. - * - * @throws Exception if an instance cannot be returned to the pool + * Close this pool, and free any resources associated with it. + *

+ * Calling {@link #addObject addObject} or + * {@link #borrowObject borrowObject} after invoking this method on a pool + * will cause them to throw an {@link IllegalStateException}. + *

+ * Implementations should silently fail if not all resources can be freed. */ - void returnObject(K key, V obj) throws Exception; + @Override + void close(); } diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/KeyedPooledObjectFactory.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/KeyedPooledObjectFactory.java index 0dd5645f7..12d85790f 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/KeyedPooledObjectFactory.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/KeyedPooledObjectFactory.java @@ -22,7 +22,6 @@ package com.fr.third.org.apache.commons.pool2; *

* By contract, when an {@link KeyedObjectPool} * delegates to a {@link KeyedPooledObjectFactory}, - *

*
    *
  1. * {@link #makeObject} is called whenever a new instance is needed. @@ -36,7 +35,7 @@ package com.fr.third.org.apache.commons.pool2; * {@link #validateObject} may be invoked on {@link #activateObject activated} * instances to make sure they can be * {@link KeyedObjectPool#borrowObject borrowed} from the pool. - * {@code validateObject} may also be used to test an + * validateObject may also be used to test an * instance being {@link KeyedObjectPool#returnObject returned} to the pool * before it is {@link #passivateObject passivated}. It will only be invoked * on an activated instance. @@ -48,7 +47,7 @@ package com.fr.third.org.apache.commons.pool2; *
  2. * {@link #destroyObject destroyObject} * is invoked on every instance when it is being "dropped" from the - * pool (whether due to the response from {@code validateObject}, + * pool (whether due to the response from validateObject, * or for reasons specific to the pool implementation.) There is no * guarantee that the instance being destroyed will * be considered active, passive or in a generally consistent state. @@ -57,14 +56,13 @@ package com.fr.third.org.apache.commons.pool2; * {@link KeyedPooledObjectFactory} must be thread-safe. The only promise * an {@link KeyedObjectPool} makes is that the same instance of an object will * not be passed to more than one method of a - * {@code KeyedPoolableObjectFactory} at a time. + * KeyedPoolableObjectFactory at a time. *

    * While clients of a {@link KeyedObjectPool} borrow and return instances of * the underlying value type V, the factory methods act on instances of * {@link PooledObject PooledObject<V>}. These are the object wrappers that * pools use to track and maintain state informations about the objects that * they manage. - *

    * * @see KeyedObjectPool * @see BaseKeyedPooledObjectFactory @@ -74,8 +72,7 @@ package com.fr.third.org.apache.commons.pool2; * * @since 2.0 */ -public interface KeyedPooledObjectFactory { - +public interface KeyedPooledObjectFactory { /** * Create an instance that can be served by the pool and * wrap it in a {@link PooledObject} to be managed by the pool. @@ -94,13 +91,11 @@ public interface KeyedPooledObjectFactory { * Destroy an instance no longer needed by the pool. *

    * It is important for implementations of this method to be aware that there - * is no guarantee about what state {@code obj} will be in and the + * is no guarantee about what state obj will be in and the * implementation should be prepared to handle unexpected errors. - *

    *

    * Also, an implementation must take in to consideration that instances lost * to the garbage collector may never be destroyed. - *

    * * @param key the key used when selecting the instance * @param p a {@code PooledObject} wrapping the instance to be destroyed @@ -113,34 +108,14 @@ public interface KeyedPooledObjectFactory { */ void destroyObject(K key, PooledObject p) throws Exception; - /** - * Destroy an instance no longer needed by the pool, using the provided {@link DestroyMode}. - * - * @param key the key used when selecting the instance - * @param p a {@code PooledObject} wrapping the instance to be destroyed - * @param mode DestroyMode providing context to the factory - * - * @throws Exception should be avoided as it may be swallowed by - * the pool implementation. - * - * @see #validateObject - * @see KeyedObjectPool#invalidateObject - * @see #destroyObject(Object, PooledObject) - * @see DestroyMode - * @since 2.9.0 - */ - default void destroyObject(final K key, final PooledObject p, final DestroyMode mode) throws Exception { - destroyObject(key, p); - } - /** * Ensures that the instance is safe to be returned by the pool. * * @param key the key used when selecting the object * @param p a {@code PooledObject} wrapping the instance to be validated * - * @return {@code false} if {@code obj} is not valid and should - * be dropped from the pool, {@code true} otherwise. + * @return false if obj is not valid and should + * be dropped from the pool, true otherwise. */ boolean validateObject(K key, PooledObject p); @@ -150,7 +125,7 @@ public interface KeyedPooledObjectFactory { * @param key the key used when selecting the object * @param p a {@code PooledObject} wrapping the instance to be activated * - * @throws Exception if there is a problem activating {@code obj}, + * @throws Exception if there is a problem activating obj, * this exception may be swallowed by the pool. * * @see #destroyObject @@ -163,7 +138,7 @@ public interface KeyedPooledObjectFactory { * @param key the key used when selecting the object * @param p a {@code PooledObject} wrapping the instance to be passivated * - * @throws Exception if there is a problem passivating {@code obj}, + * @throws Exception if there is a problem passivating obj, * this exception may be swallowed by the pool. * * @see #destroyObject diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/ObjectPool.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/ObjectPool.java index 11c1f51a1..cc0735ef8 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/ObjectPool.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/ObjectPool.java @@ -23,7 +23,6 @@ import java.util.NoSuchElementException; * A pooling simple interface. *

    * Example of use: - *

    *
     Object obj = null;
      *
    @@ -47,7 +46,6 @@ import java.util.NoSuchElementException;
      * }
    *

    * See {@link BaseObjectPool} for a simple base implementation. - *

    * * @param Type of element pooled in this pool. * @@ -58,39 +56,6 @@ import java.util.NoSuchElementException; * @since 2.0 */ public interface ObjectPool extends Closeable { - - /** - * Creates an object using the {@link PooledObjectFactory factory} or other - * implementation dependent mechanism, passivate it, and then place it in - * the idle object pool. {@code addObject} is useful for "pre-loading" - * a pool with idle objects. (Optional operation). - * - * @throws Exception - * when {@link PooledObjectFactory#makeObject} fails. - * @throws IllegalStateException - * after {@link #close} has been called on this pool. - * @throws UnsupportedOperationException - * when this pool cannot add new idle objects. - */ - void addObject() throws Exception, IllegalStateException, - UnsupportedOperationException; - - /** - * Calls {@link ObjectPool#addObject()} {@code count} - * number of times. - * - * @param count - * the number of idle objects to add. - * @throws Exception - * when {@link ObjectPool#addObject()} fails. - * @since 2.8.0 - */ - default void addObjects(final int count) throws Exception { - for (int i = 0; i < count; i++) { - addObject(); - } - } - /** * Obtains an instance from this pool. *

    @@ -99,17 +64,14 @@ public interface ObjectPool extends Closeable { * idle object and have been activated with * {@link PooledObjectFactory#activateObject} and then validated with * {@link PooledObjectFactory#validateObject}. - *

    *

    * By contract, clients must return the borrowed instance * using {@link #returnObject}, {@link #invalidateObject}, or a related * method as defined in an implementation or sub-interface. - *

    *

    - * The behavior of this method when the pool has been exhausted + * The behaviour of this method when the pool has been exhausted * is not strictly specified (although it may be specified by * implementations). - *

    * * @return an instance from this pool. * @@ -126,39 +88,57 @@ public interface ObjectPool extends Closeable { IllegalStateException; /** - * Clears any objects sitting idle in the pool, releasing any associated - * resources (optional operation). Idle objects cleared must be - * {@link PooledObjectFactory#destroyObject(PooledObject)}. + * Return an instance to the pool. By contract, obj + * must have been obtained using {@link #borrowObject()} or + * a related method as defined in an implementation or sub-interface. * - * @throws UnsupportedOperationException - * if this implementation does not support the operation + * @param obj a {@link #borrowObject borrowed} instance to be returned. * - * @throws Exception if the pool cannot be cleared + * @throws IllegalStateException + * if an attempt is made to return an object to the pool that + * is in any state other than allocated (i.e. borrowed). + * Attempting to return an object more than once or attempting + * to return an object that was never borrowed from the pool + * will trigger this exception. + * + * @throws Exception if an instance cannot be returned to the pool */ - void clear() throws Exception, UnsupportedOperationException; + void returnObject(T obj) throws Exception; /** - * Closes this pool, and free any resources associated with it. + * Invalidates an object from the pool. *

    - * Calling {@link #addObject} or {@link #borrowObject} after invoking this - * method on a pool will cause them to throw an {@link IllegalStateException}. - *

    + * By contract, obj must have been obtained + * using {@link #borrowObject} or a related method as defined in an + * implementation or sub-interface. *

    - * Implementations should silently fail if not all resources can be freed. - *

    + * This method should be used when an object that has been borrowed is + * determined (due to an exception or other problem) to be invalid. + * + * @param obj a {@link #borrowObject borrowed} instance to be disposed. + * + * @throws Exception if the instance cannot be invalidated */ - @Override - void close(); + void invalidateObject(T obj) throws Exception; /** - * Returns the number of instances currently borrowed from this pool. Returns - * a negative value if this information is not available. - * @return the number of instances currently borrowed from this pool. + * Create an object using the {@link PooledObjectFactory factory} or other + * implementation dependent mechanism, passivate it, and then place it in + * the idle object pool. addObject is useful for "pre-loading" + * a pool with idle objects. (Optional operation). + * + * @throws Exception + * when {@link PooledObjectFactory#makeObject} fails. + * @throws IllegalStateException + * after {@link #close} has been called on this pool. + * @throws UnsupportedOperationException + * when this pool cannot add new idle objects. */ - int getNumActive(); + void addObject() throws Exception, IllegalStateException, + UnsupportedOperationException; /** - * Returns the number of instances currently idle in this pool. This may be + * Return the number of instances currently idle in this pool. This may be * considered an approximation of the number of objects that can be * {@link #borrowObject borrowed} without creating any new instances. * Returns a negative value if this information is not available. @@ -167,62 +147,32 @@ public interface ObjectPool extends Closeable { int getNumIdle(); /** - * Invalidates an object from the pool. - *

    - * By contract, {@code obj} must have been obtained - * using {@link #borrowObject} or a related method as defined in an - * implementation or sub-interface. - *

    - *

    - * This method should be used when an object that has been borrowed is - * determined (due to an exception or other problem) to be invalid. - *

    - * - * @param obj a {@link #borrowObject borrowed} instance to be disposed. - * - * @throws Exception if the instance cannot be invalidated + * Return the number of instances currently borrowed from this pool. Returns + * a negative value if this information is not available. + * @return the number of instances currently borrowed from this pool. */ - void invalidateObject(T obj) throws Exception; + int getNumActive(); /** - * Invalidates an object from the pool, using the provided - * {@link DestroyMode} - *

    - * By contract, {@code obj} must have been obtained - * using {@link #borrowObject} or a related method as defined in an - * implementation or sub-interface. - *

    - *

    - * This method should be used when an object that has been borrowed is - * determined (due to an exception or other problem) to be invalid. - *

    + * Clears any objects sitting idle in the pool, releasing any associated + * resources (optional operation). Idle objects cleared must be + * {@link PooledObjectFactory#destroyObject(PooledObject)}. * - * @param obj a {@link #borrowObject borrowed} instance to be disposed. - * @param mode destroy activation context provided to the factory + * @throws UnsupportedOperationException + * if this implementation does not support the operation * - * @throws Exception if the instance cannot be invalidated - * @since 2.9.0 + * @throws Exception if the pool cannot be cleared */ - default void invalidateObject(final T obj, final DestroyMode mode) throws Exception { - invalidateObject(obj); - } + void clear() throws Exception, UnsupportedOperationException; /** - * Returns an instance to the pool. By contract, {@code obj} - * must have been obtained using {@link #borrowObject()} or - * a related method as defined in an implementation or sub-interface. - * - * @param obj a {@link #borrowObject borrowed} instance to be returned. - * - * @throws IllegalStateException - * if an attempt is made to return an object to the pool that - * is in any state other than allocated (i.e. borrowed). - * Attempting to return an object more than once or attempting - * to return an object that was never borrowed from the pool - * will trigger this exception. - * - * @throws Exception if an instance cannot be returned to the pool + * Close this pool, and free any resources associated with it. + *

    + * Calling {@link #addObject} or {@link #borrowObject} after invoking this + * method on a pool will cause them to throw an {@link IllegalStateException}. + *

    + * Implementations should silently fail if not all resources can be freed. */ - void returnObject(T obj) throws Exception; - + @Override + void close(); } diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PoolUtils.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PoolUtils.java index f2a122af2..8f6d515e5 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PoolUtils.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PoolUtils.java @@ -36,13 +36,6 @@ import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; */ public final class PoolUtils { - private static final String MSG_FACTOR_NEGATIVE = "factor must be positive."; - private static final String MSG_MIN_IDLE = "minIdle must be non-negative."; - static final String MSG_NULL_KEY = "key must not be null."; - private static final String MSG_NULL_KEYED_POOL = "keyedPool must not be null."; - static final String MSG_NULL_KEYS = "keys must not be null."; - private static final String MSG_NULL_POOL = "pool must not be null."; - /** * Timer used to periodically check pools idle object count. Because a * {@link Timer} creates a {@link Thread}, an IODH is used. @@ -100,20 +93,20 @@ public final class PoolUtils { * @return the {@link TimerTask} that will periodically check the pools idle * object count. * @throws IllegalArgumentException - * when {@code pool} is {@code null} or when {@code minIdle} is - * negative or when {@code period} isn't valid for - * {@link Timer#schedule(TimerTask, long, long)} + * when pool is null or when + * minIdle is negative or when period + * isn't valid for {@link Timer#schedule(TimerTask, long, long)} */ public static TimerTask checkMinIdle(final ObjectPool pool, final int minIdle, final long period) throws IllegalArgumentException { if (pool == null) { - throw new IllegalArgumentException(MSG_NULL_KEYED_POOL); + throw new IllegalArgumentException("keyedPool must not be null."); } if (minIdle < 0) { - throw new IllegalArgumentException(MSG_MIN_IDLE); + throw new IllegalArgumentException("minIdle must be non-negative."); } - final TimerTask task = new ObjectPoolMinIdleTimerTask<>(pool, minIdle); + final TimerTask task = new ObjectPoolMinIdleTimerTask(pool, minIdle); getMinIdleTimer().schedule(task, 0L, period); return task; } @@ -139,24 +132,25 @@ public final class PoolUtils { * @return the {@link TimerTask} that will periodically check the pools idle * object count. * @throws IllegalArgumentException - * when {@code keyedPool}, {@code key} is {@code null} or - * when {@code minIdle} is negative or when {@code period} isn't - * valid for {@link Timer#schedule(TimerTask, long, long)}. + * when keyedPool, key is + * null or when minIdle is negative or + * when period isn't valid for + * {@link Timer#schedule(TimerTask, long, long)}. */ public static TimerTask checkMinIdle( final KeyedObjectPool keyedPool, final K key, final int minIdle, final long period) throws IllegalArgumentException { if (keyedPool == null) { - throw new IllegalArgumentException(MSG_NULL_KEYED_POOL); + throw new IllegalArgumentException("keyedPool must not be null."); } if (key == null) { - throw new IllegalArgumentException(MSG_NULL_KEY); + throw new IllegalArgumentException("key must not be null."); } if (minIdle < 0) { - throw new IllegalArgumentException(MSG_MIN_IDLE); + throw new IllegalArgumentException("minIdle must be non-negative."); } - final TimerTask task = new KeyedObjectPoolMinIdleTimerTask<>( + final TimerTask task = new KeyedObjectPoolMinIdleTimerTask( keyedPool, key, minIdle); getMinIdleTimer().schedule(task, 0L, period); return task; @@ -164,8 +158,8 @@ public final class PoolUtils { /** * Periodically check the idle object count for each key in the - * {@code Collection keys} in the keyedPool. At most one idle object will be - * added per period. + * Collection keys in the keyedPool. At most one + * idle object will be added per period. * * @param keyedPool * the keyedPool to check periodically. @@ -182,10 +176,11 @@ public final class PoolUtils { * @return a {@link Map} of key and {@link TimerTask} pairs that will * periodically check the pools idle object count. * @throws IllegalArgumentException - * when {@code keyedPool}, {@code keys}, or any of the values in - * the collection is {@code null} or when {@code minIdle} is - * negative or when {@code period} isn't valid for - * {@link Timer#schedule(TimerTask, long, long)}. + * when keyedPool, keys, or any of the + * values in the collection is null or when + * minIdle is negative or when period + * isn't valid for {@link Timer#schedule(TimerTask, long, long)} + * . * @see #checkMinIdle(KeyedObjectPool, Object, int, long) */ public static Map checkMinIdle( @@ -193,9 +188,9 @@ public final class PoolUtils { final int minIdle, final long period) throws IllegalArgumentException { if (keys == null) { - throw new IllegalArgumentException(MSG_NULL_KEYS); + throw new IllegalArgumentException("keys must not be null."); } - final Map tasks = new HashMap<>(keys.size()); + final Map tasks = new HashMap(keys.size()); final Iterator iter = keys.iterator(); while (iter.hasNext()) { final K key = iter.next(); @@ -206,8 +201,8 @@ public final class PoolUtils { } /** - * Calls {@link ObjectPool#addObject()} on {@code pool} {@code count} number - * of times. + * Call addObject() on pool count + * number of times. * * @param pool * the pool to prefill. @@ -217,76 +212,81 @@ public final class PoolUtils { * @throws Exception * when {@link ObjectPool#addObject()} fails. * @throws IllegalArgumentException - * when {@code pool} is {@code null}. - * @deprecated Use {@link ObjectPool#addObjects(int)}. + * when pool is null. */ - @Deprecated public static void prefill(final ObjectPool pool, final int count) throws Exception, IllegalArgumentException { if (pool == null) { - throw new IllegalArgumentException(MSG_NULL_POOL); + throw new IllegalArgumentException("pool must not be null."); + } + for (int i = 0; i < count; i++) { + pool.addObject(); } - pool.addObjects(count); } /** - * Calls {@link KeyedObjectPool#addObject(Object)} on {@code keyedPool} with - * {@code key} {@code count} number of times. + * Call addObject(Object) on keyedPool with + * key count number of times. * * @param keyedPool * the keyedPool to prefill. * @param key * the key to add objects for. * @param count - * the number of idle objects to add for {@code key}. + * the number of idle objects to add for key. * @param the type of the pool key * @param the type of pool entries * @throws Exception * when {@link KeyedObjectPool#addObject(Object)} fails. * @throws IllegalArgumentException - * when {@code keyedPool} or {@code key} is {@code null}. - * @deprecated Use {@link KeyedObjectPool#addObjects(Object, int)}. + * when keyedPool or key is + * null. */ - @Deprecated public static void prefill(final KeyedObjectPool keyedPool, final K key, final int count) throws Exception, IllegalArgumentException { if (keyedPool == null) { - throw new IllegalArgumentException(MSG_NULL_KEYED_POOL); + throw new IllegalArgumentException("keyedPool must not be null."); + } + if (key == null) { + throw new IllegalArgumentException("key must not be null."); + } + for (int i = 0; i < count; i++) { + keyedPool.addObject(key); } - keyedPool.addObjects(key, count); } /** - * Calls {@link KeyedObjectPool#addObject(Object)} on {@code keyedPool} with - * each key in {@code keys} for {@code count} number of times. This has + * Call addObject(Object) on keyedPool with each + * key in keys for count number of times. This has * the same effect as calling {@link #prefill(KeyedObjectPool, Object, int)} - * for each key in the {@code keys} collection. + * for each key in the keys collection. * * @param keyedPool * the keyedPool to prefill. * @param keys * {@link Collection} of keys to add objects for. * @param count - * the number of idle objects to add for each {@code key}. + * the number of idle objects to add for each key. * @param the type of the pool key * @param the type of pool entries * @throws Exception * when {@link KeyedObjectPool#addObject(Object)} fails. * @throws IllegalArgumentException - * when {@code keyedPool}, {@code keys}, or any value in - * {@code keys} is {@code null}. + * when keyedPool, keys, or any value + * in keys is null. * @see #prefill(KeyedObjectPool, Object, int) - * @deprecated Use {@link KeyedObjectPool#addObjects(Collection, int)}. */ - @Deprecated public static void prefill(final KeyedObjectPool keyedPool, final Collection keys, final int count) throws Exception, IllegalArgumentException { if (keys == null) { - throw new IllegalArgumentException(MSG_NULL_KEYS); + throw new IllegalArgumentException("keys must not be null."); + } + final Iterator iter = keys.iterator(); + while (iter.hasNext()) { + prefill(keyedPool, iter.next(), count); } - keyedPool.addObjects(keys, count); } /** @@ -304,13 +304,11 @@ public final class PoolUtils { * @param pool * the ObjectPool to be "wrapped" in a synchronized ObjectPool. * @param the type of objects in the pool - * @throws IllegalArgumentException - * when {@code pool} is {@code null}. * @return a synchronized view of the specified ObjectPool. */ public static ObjectPool synchronizedPool(final ObjectPool pool) { if (pool == null) { - throw new IllegalArgumentException(MSG_NULL_POOL); + throw new IllegalArgumentException("pool must not be null."); } /* * assert !(pool instanceof GenericObjectPool) : @@ -323,7 +321,7 @@ public final class PoolUtils { * .equals(pool.getClass().getName()) : * "CompositeObjectPools are already thread-safe"; */ - return new SynchronizedObjectPool<>(pool); + return new SynchronizedObjectPool(pool); } /** @@ -356,7 +354,7 @@ public final class PoolUtils { * .equals(keyedPool.getClass().getName()) : * "CompositeKeyedObjectPools are already thread-safe"; */ - return new SynchronizedKeyedObjectPool<>(keyedPool); + return new SynchronizedKeyedObjectPool(keyedPool); } /** @@ -371,7 +369,7 @@ public final class PoolUtils { */ public static PooledObjectFactory synchronizedPooledFactory( final PooledObjectFactory factory) { - return new SynchronizedPooledObjectFactory<>(factory); + return new SynchronizedPooledObjectFactory(factory); } /** @@ -387,7 +385,7 @@ public final class PoolUtils { */ public static KeyedPooledObjectFactory synchronizedKeyedPooledFactory( final KeyedPooledObjectFactory keyedFactory) { - return new SynchronizedKeyedPooledObjectFactory<>(keyedFactory); + return new SynchronizedKeyedPooledObjectFactory(keyedFactory); } /** @@ -401,8 +399,6 @@ public final class PoolUtils { * the ObjectPool to be decorated so it shrinks its idle count * when possible. * @param the type of objects in the pool - * @throws IllegalArgumentException - * when {@code pool} is {@code null}. * @return a pool that adaptively decreases its size when idle objects are * no longer needed. * @see #erodingPool(ObjectPool, float) @@ -433,9 +429,6 @@ public final class PoolUtils { * shrinks more aggressively. If 1 < factor then the pool * shrinks less aggressively. * @param the type of objects in the pool - * @throws IllegalArgumentException - * when {@code pool} is {@code null} or when {@code factor} is - * not positive. * @return a pool that adaptively decreases its size when idle objects are * no longer needed. * @see #erodingPool(ObjectPool) @@ -443,12 +436,12 @@ public final class PoolUtils { public static ObjectPool erodingPool(final ObjectPool pool, final float factor) { if (pool == null) { - throw new IllegalArgumentException(MSG_NULL_POOL); + throw new IllegalArgumentException("pool must not be null."); } if (factor <= 0f) { - throw new IllegalArgumentException(MSG_FACTOR_NEGATIVE); + throw new IllegalArgumentException("factor must be positive."); } - return new ErodingObjectPool<>(pool, factor); + return new ErodingObjectPool(pool, factor); } /** @@ -463,8 +456,6 @@ public final class PoolUtils { * count when possible. * @param the type of the pool key * @param the type of pool entries - * @throws IllegalArgumentException - * when {@code keyedPool} is {@code null}. * @return a pool that adaptively decreases its size when idle objects are * no longer needed. * @see #erodingPool(KeyedObjectPool, float) @@ -498,9 +489,6 @@ public final class PoolUtils { * shrinks less aggressively. * @param the type of the pool key * @param the type of pool entries - * @throws IllegalArgumentException - * when {@code keyedPool} is {@code null} or when {@code factor} - * is not positive. * @return a pool that adaptively decreases its size when idle objects are * no longer needed. * @see #erodingPool(KeyedObjectPool, float, boolean) @@ -541,9 +529,6 @@ public final class PoolUtils { * when true, each key is treated independently. * @param the type of the pool key * @param the type of pool entries - * @throws IllegalArgumentException - * when {@code keyedPool} is {@code null} or when {@code factor} - * is not positive. * @return a pool that adaptively decreases its size when idle objects are * no longer needed. * @see #erodingPool(KeyedObjectPool) @@ -553,19 +538,19 @@ public final class PoolUtils { final KeyedObjectPool keyedPool, final float factor, final boolean perKey) { if (keyedPool == null) { - throw new IllegalArgumentException(MSG_NULL_KEYED_POOL); + throw new IllegalArgumentException("keyedPool must not be null."); } if (factor <= 0f) { - throw new IllegalArgumentException(MSG_FACTOR_NEGATIVE); + throw new IllegalArgumentException("factor must be positive."); } if (perKey) { - return new ErodingPerKeyKeyedObjectPool<>(keyedPool, factor); + return new ErodingPerKeyKeyedObjectPool(keyedPool, factor); } - return new ErodingKeyedObjectPool<>(keyedPool, factor); + return new ErodingKeyedObjectPool(keyedPool, factor); } /** - * Gets the {@code Timer} for checking keyedPool's idle count. + * Get the Timer for checking keyedPool's idle count. * * @return the {@link Timer} for checking keyedPool's idle count. */ @@ -602,7 +587,7 @@ public final class PoolUtils { ObjectPoolMinIdleTimerTask(final ObjectPool pool, final int minIdle) throws IllegalArgumentException { if (pool == null) { - throw new IllegalArgumentException(MSG_NULL_POOL); + throw new IllegalArgumentException("pool must not be null."); } this.pool = pool; this.minIdle = minIdle; @@ -654,7 +639,6 @@ public final class PoolUtils { */ private static final class KeyedObjectPoolMinIdleTimerTask extends TimerTask { - /** Minimum number of idle instances. Not the same as pool.getMinIdle(). */ private final int minIdle; @@ -665,7 +649,7 @@ public final class PoolUtils { private final KeyedObjectPool keyedPool; /** - * Creates a new KeyedObjecPoolMinIdleTimerTask. + * Create a new KeyedObjecPoolMinIdleTimerTask. * * @param keyedPool * keyed object pool @@ -680,7 +664,7 @@ public final class PoolUtils { final K key, final int minIdle) throws IllegalArgumentException { if (keyedPool == null) { throw new IllegalArgumentException( - MSG_NULL_KEYED_POOL); + "keyedPool must not be null."); } this.keyedPool = keyedPool; this.key = key; @@ -751,7 +735,7 @@ public final class PoolUtils { private final ObjectPool pool; /** - * Creates a new SynchronizedObjectPool wrapping the given pool. + * Create a new SynchronizedObjectPool wrapping the given pool. * * @param pool * the ObjectPool to be "wrapped" in a synchronized @@ -762,7 +746,7 @@ public final class PoolUtils { SynchronizedObjectPool(final ObjectPool pool) throws IllegalArgumentException { if (pool == null) { - throw new IllegalArgumentException(MSG_NULL_POOL); + throw new IllegalArgumentException("pool must not be null."); } this.pool = pool; } @@ -928,7 +912,7 @@ public final class PoolUtils { private final KeyedObjectPool keyedPool; /** - * Creates a new SynchronizedKeyedObjectPool wrapping the given pool + * Create a new SynchronizedKeyedObjectPool wrapping the given pool * * @param keyedPool * KeyedObjectPool to wrap @@ -939,7 +923,7 @@ public final class PoolUtils { throws IllegalArgumentException { if (keyedPool == null) { throw new IllegalArgumentException( - MSG_NULL_KEYED_POOL); + "keyedPool must not be null."); } this.keyedPool = keyedPool; } @@ -1134,7 +1118,6 @@ public final class PoolUtils { */ private static final class SynchronizedPooledObjectFactory implements PooledObjectFactory { - /** Synchronization lock */ private final WriteLock writeLock = new ReentrantReadWriteLock().writeLock(); @@ -1142,7 +1125,7 @@ public final class PoolUtils { private final PooledObjectFactory factory; /** - * Creates a SynchronizedPoolableObjectFactory wrapping the given + * Create a SynchronizedPoolableObjectFactory wrapping the given * factory. * * @param factory @@ -1251,7 +1234,6 @@ public final class PoolUtils { */ private static final class SynchronizedKeyedPooledObjectFactory implements KeyedPooledObjectFactory { - /** Synchronization lock */ private final WriteLock writeLock = new ReentrantReadWriteLock().writeLock(); @@ -1259,7 +1241,7 @@ public final class PoolUtils { private final KeyedPooledObjectFactory keyedFactory; /** - * Creates a SynchronizedKeyedPoolableObjectFactory wrapping the given + * Create a SynchronizedKeyedPoolableObjectFactory wrapping the given * factory. * * @param keyedFactory @@ -1376,7 +1358,7 @@ public final class PoolUtils { private transient volatile int idleHighWaterMark; /** - * Creates a new ErodingFactor with the given erosion factor. + * Create a new ErodingFactor with the given erosion factor. * * @param factor * erosion factor @@ -1436,7 +1418,6 @@ public final class PoolUtils { * @param type of objects in the pool */ private static class ErodingObjectPool implements ObjectPool { - /** Underlying object pool */ private final ObjectPool pool; @@ -1444,7 +1425,7 @@ public final class PoolUtils { private final ErodingFactor factor; /** - * Creates an ErodingObjectPool wrapping the given pool using the + * Create an ErodingObjectPool wrapping the given pool using the * specified erosion factor. * * @param pool @@ -1582,7 +1563,6 @@ public final class PoolUtils { */ private static class ErodingKeyedObjectPool implements KeyedObjectPool { - /** Underlying pool */ private final KeyedObjectPool keyedPool; @@ -1590,7 +1570,7 @@ public final class PoolUtils { private final ErodingFactor erodingFactor; /** - * Creates an ErodingObjectPool wrapping the given pool using the + * Create an ErodingObjectPool wrapping the given pool using the * specified erosion factor. * * @param keyedPool @@ -1606,7 +1586,7 @@ public final class PoolUtils { } /** - * Creates an ErodingObjectPool wrapping the given pool using the + * Create an ErodingObjectPool wrapping the given pool using the * specified erosion factor. * * @param keyedPool @@ -1614,13 +1594,13 @@ public final class PoolUtils { * @param erodingFactor * erosion factor - determines the frequency of erosion * events - * @see #erodingFactor + * @see #factor */ protected ErodingKeyedObjectPool(final KeyedObjectPool keyedPool, final ErodingFactor erodingFactor) { if (keyedPool == null) { throw new IllegalArgumentException( - MSG_NULL_KEYED_POOL); + "keyedPool must not be null."); } this.keyedPool = keyedPool; this.erodingFactor = erodingFactor; @@ -1796,7 +1776,6 @@ public final class PoolUtils { */ private static final class ErodingPerKeyKeyedObjectPool extends ErodingKeyedObjectPool { - /** Erosion factor - same for all pools */ private final float factor; @@ -1804,7 +1783,7 @@ public final class PoolUtils { private final Map factors = Collections.synchronizedMap(new HashMap()); /** - * Creates a new ErordingPerKeyKeyedObjectPool decorating the given keyed + * Create a new ErordingPerKeyKeyedObjectPool decorating the given keyed * pool with the specified erosion factor. * * @param keyedPool @@ -1836,11 +1815,10 @@ public final class PoolUtils { /** * {@inheritDoc} */ - @SuppressWarnings("resource") // getKeyedPool(): ivar access @Override public String toString() { return "ErodingPerKeyKeyedObjectPool{" + "factor=" + factor + ", keyedPool=" + getKeyedPool() + '}'; } } -} +} \ No newline at end of file diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PooledObject.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PooledObject.java index 0c201f2b4..9e1cd72cf 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PooledObject.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PooledObject.java @@ -24,7 +24,6 @@ import java.util.Deque; * state, for the pooled objects. *

    * Implementations of this class are required to be thread-safe. - *

    * * @param the type of object in the pool * @@ -33,7 +32,7 @@ import java.util.Deque; public interface PooledObject extends Comparable> { /** - * Obtains the underlying object that is wrapped by this instance of + * Obtain the underlying object that is wrapped by this instance of * {@link PooledObject}. * * @return The wrapped object @@ -41,7 +40,7 @@ public interface PooledObject extends Comparable> { T getObject(); /** - * Obtains the time (using the same basis as + * Obtain the time (using the same basis as * {@link System#currentTimeMillis()}) that this object was created. * * @return The creation time for the wrapped object @@ -49,7 +48,7 @@ public interface PooledObject extends Comparable> { long getCreateTime(); /** - * Obtains the time in milliseconds that this object last spent in the + * Obtain the time in milliseconds that this object last spent in the * active state (it may still be active in which case subsequent calls will * return an increased value). * @@ -58,17 +57,7 @@ public interface PooledObject extends Comparable> { long getActiveTimeMillis(); /** - * Gets the number of times this object has been borrowed. - * - * @return -1 by default for old implementations prior to release 2.7.0. - * @since 2.7.0 - */ - default long getBorrowedCount() { - return -1; - } - - /** - * Obtains the time in milliseconds that this object last spend in the + * Obtain the time in milliseconds that this object last spend in the * idle state (it may still be idle in which case subsequent calls will * return an increased value). * @@ -77,21 +66,21 @@ public interface PooledObject extends Comparable> { long getIdleTimeMillis(); /** - * Obtains the time the wrapped object was last borrowed. + * Obtain the time the wrapped object was last borrowed. * * @return The time the object was last borrowed */ long getLastBorrowTime(); /** - * Obtains the time the wrapped object was last returned. + * Obtain the time the wrapped object was last returned. * * @return The time the object was last returned */ long getLastReturnTime(); /** - * Returns an estimate of the last time this object was used. If the class + * Return an estimate of the last time this object was used. If the class * of the pooled object implements {@link TrackedUse}, what is returned is * the maximum of {@link TrackedUse#getLastUsed()} and * {@link #getLastBorrowTime()}; otherwise this method gives the same @@ -107,10 +96,8 @@ public interface PooledObject extends Comparable> { *

    * Note: This class has a natural ordering that is inconsistent with * equals if distinct objects have the same identity hash code. - *

    *

    * {@inheritDoc} - *

    */ @Override int compareTo(PooledObject other); @@ -131,12 +118,12 @@ public interface PooledObject extends Comparable> { String toString(); /** - * Attempts to place the pooled object in the + * Attempt to place the pooled object in the * {@link PooledObjectState#EVICTION} state. * - * @return {@code true} if the object was placed in the + * @return true if the object was placed in the * {@link PooledObjectState#EVICTION} state otherwise - * {@code false} + * false */ boolean startEvictionTest(); @@ -180,17 +167,17 @@ public interface PooledObject extends Comparable> { */ void setLogAbandoned(boolean logAbandoned); - /** - * Configures the stack trace generation strategy based on whether or not fully detailed stack traces are required. - * When set to false, abandoned logs may only include caller class information rather than method names, line - * numbers, and other normal metadata available in a full stack trace. - * - * @param requireFullStackTrace the new configuration setting for abandoned object logging - * @since 2.7.0 - */ - default void setRequireFullStackTrace(final boolean requireFullStackTrace) { - // noop - } +// TODO: uncomment in 3.0 (API compatibility) +// /** +// * Configures the stack trace generation strategy based on whether or not fully +// * detailed stack traces are required. When set to false, abandoned logs may +// * only include caller class information rather than method names, line numbers, +// * and other normal metadata available in a full stack trace. +// * +// * @param requireFullStackTrace the new configuration setting for abandoned object +// * logging +// */ +// void setRequireFullStackTrace(boolean requireFullStackTrace); /** * Record the current stack trace as the last time the object was used. @@ -222,4 +209,10 @@ public interface PooledObject extends Comparable> { */ void markReturning(); + // TODO: Uncomment this for version 3 (can't add it to 2.x as it will break + // API compatibility) + ///** + // * Get the number of times this object has been borrowed. + // */ + //long getBorrowedCount(); } diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PooledObjectFactory.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PooledObjectFactory.java index 927e76e7e..7dc6e7df1 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PooledObjectFactory.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PooledObjectFactory.java @@ -22,7 +22,6 @@ package com.fr.third.org.apache.commons.pool2; *

    * By contract, when an {@link ObjectPool} delegates to a * {@link PooledObjectFactory}, - *

    *
      *
    1. * {@link #makeObject} is called whenever a new instance is needed. @@ -54,7 +53,7 @@ package com.fr.third.org.apache.commons.pool2; *
    * {@link PooledObjectFactory} must be thread-safe. The only promise * an {@link ObjectPool} makes is that the same instance of an object will not - * be passed to more than one method of a {@code PoolableObjectFactory} + * be passed to more than one method of a PoolableObjectFactory * at a time. *

    * While clients of a {@link KeyedObjectPool} borrow and return instances of @@ -62,7 +61,6 @@ package com.fr.third.org.apache.commons.pool2; * {@link PooledObject PooledObject<V>}. These are the object wrappers that * pools use to track and maintain state information about the objects that * they manage. - *

    * * @param Type of element managed in this factory. * @@ -71,9 +69,8 @@ package com.fr.third.org.apache.commons.pool2; * @since 2.0 */ public interface PooledObjectFactory { - /** - * Creates an instance that can be served by the pool and wrap it in a + * Create an instance that can be served by the pool and wrap it in a * {@link PooledObject} to be managed by the pool. * * @return a {@code PooledObject} wrapping an instance that can be served by the pool @@ -84,13 +81,11 @@ public interface PooledObjectFactory { PooledObject makeObject() throws Exception; /** - * Destroys an instance no longer needed by the pool, using the default (NORMAL) - * DestroyMode. + * Destroys an instance no longer needed by the pool. *

    * It is important for implementations of this method to be aware that there - * is no guarantee about what state {@code obj} will be in and the + * is no guarantee about what state obj will be in and the * implementation should be prepared to handle unexpected errors. - *

    *

    * Also, an implementation must take in to consideration that instances lost * to the garbage collector may never be destroyed. @@ -106,42 +101,22 @@ public interface PooledObjectFactory { */ void destroyObject(PooledObject p) throws Exception; - /** - * Destroys an instance no longer needed by the pool, using the provided - * DestroyMode. - * - * @param p a {@code PooledObject} wrapping the instance to be destroyed - * @param mode DestroyMode providing context to the factory - * - * @throws Exception should be avoided as it may be swallowed by - * the pool implementation. - * - * @see #validateObject - * @see ObjectPool#invalidateObject - * @see #destroyObject(PooledObject) - * @see DestroyMode - * @since 2.9.0 - */ - default void destroyObject(final PooledObject p, final DestroyMode mode) throws Exception { - destroyObject(p); - } - /** * Ensures that the instance is safe to be returned by the pool. * * @param p a {@code PooledObject} wrapping the instance to be validated * - * @return {@code false} if {@code obj} is not valid and should - * be dropped from the pool, {@code true} otherwise. + * @return false if obj is not valid and should + * be dropped from the pool, true otherwise. */ boolean validateObject(PooledObject p); /** - * Reinitializes an instance to be returned by the pool. + * Reinitialize an instance to be returned by the pool. * * @param p a {@code PooledObject} wrapping the instance to be activated * - * @throws Exception if there is a problem activating {@code obj}, + * @throws Exception if there is a problem activating obj, * this exception may be swallowed by the pool. * * @see #destroyObject @@ -149,11 +124,11 @@ public interface PooledObjectFactory { void activateObject(PooledObject p) throws Exception; /** - * Uninitializes an instance to be returned to the idle object pool. + * Uninitialize an instance to be returned to the idle object pool. * * @param p a {@code PooledObject} wrapping the instance to be passivated * - * @throws Exception if there is a problem passivating {@code obj}, + * @throws Exception if there is a problem passivating obj, * this exception may be swallowed by the pool. * * @see #destroyObject diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PooledObjectState.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PooledObjectState.java index 22f1901ad..2469abf5a 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PooledObjectState.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PooledObjectState.java @@ -22,7 +22,6 @@ package com.fr.third.org.apache.commons.pool2; * @since 2.0 */ public enum PooledObjectState { - /** * In the queue, not in use. */ diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/AbandonedConfig.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/AbandonedConfig.java index 2f4a1f209..b19f3ef99 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/AbandonedConfig.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/AbandonedConfig.java @@ -17,13 +17,11 @@ package com.fr.third.org.apache.commons.pool2.impl; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.nio.charset.Charset; - import com.fr.third.org.apache.commons.pool2.TrackedUse; import com.fr.third.org.apache.commons.pool2.UsageTracking; +import java.io.PrintWriter; + /** * Configuration settings for abandoned object removal. * @@ -44,7 +42,7 @@ public class AbandonedConfig { * *

    If set to true, abandoned objects are removed by borrowObject if * there are fewer than 2 idle objects available in the pool and - * {@code getNumActive() > getMaxTotal() - 3}

    + * getNumActive() > getMaxTotal() - 3

    * * @return true if abandoned objects are to be removed by borrowObject */ @@ -204,7 +202,7 @@ public class AbandonedConfig { * @see #getRequireFullStackTrace() * @since 2.5 */ - public void setRequireFullStackTrace(final boolean requireFullStackTrace) { + public void setRequireFullStackTrace(boolean requireFullStackTrace) { this.requireFullStackTrace = requireFullStackTrace; } @@ -212,7 +210,7 @@ public class AbandonedConfig { * PrintWriter to use to log information on abandoned objects. * Use of default system encoding is deliberate. */ - private PrintWriter logWriter = new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset())); + private PrintWriter logWriter = new PrintWriter(System.out); /** * Returns the log writer being used by this configuration to log @@ -247,7 +245,7 @@ public class AbandonedConfig { * stack trace every time a method is called on a pooled object and retain * the most recent stack trace to aid debugging of abandoned objects? * - * @return {@code true} if usage tracking is enabled + * @return true if usage tracking is enabled */ public boolean getUseUsageTracking() { return useUsageTracking; @@ -259,7 +257,7 @@ public class AbandonedConfig { * object and retain the most recent stack trace to aid debugging of * abandoned objects. * - * @param useUsageTracking A value of {@code true} will enable + * @param useUsageTracking A value of true will enable * the recording of a stack trace on every use * of a pooled object */ diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/BaseGenericObjectPool.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/BaseGenericObjectPool.java index d56818925..a8ded3f9a 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/BaseGenericObjectPool.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/BaseGenericObjectPool.java @@ -26,7 +26,6 @@ import java.util.Arrays; import java.util.Deque; import java.util.Iterator; import java.util.TimerTask; -import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; @@ -40,7 +39,6 @@ import javax.management.ObjectName; import com.fr.third.org.apache.commons.pool2.BaseObject; import com.fr.third.org.apache.commons.pool2.PooledObject; -import com.fr.third.org.apache.commons.pool2.PooledObjectState; import com.fr.third.org.apache.commons.pool2.SwallowedExceptionListener; /** @@ -63,8 +61,6 @@ public abstract class BaseGenericObjectPool extends BaseObject { */ public static final int MEAN_TIMING_STATS_CACHE_SIZE = 100; - private static final String EVICTION_POLICY_TYPE_NAME = EvictionPolicy.class.getName(); - // Configuration attributes private volatile int maxTotal = GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL; @@ -111,7 +107,7 @@ public abstract class BaseGenericObjectPool extends BaseObject { // Monitoring (primarily JMX) attributes - private final ObjectName objectName; + private final ObjectName oname; private final String creationStackTrace; private final AtomicLong borrowedCount = new AtomicLong(0); private final AtomicLong returnedCount = new AtomicLong(0); @@ -135,12 +131,12 @@ public abstract class BaseGenericObjectPool extends BaseObject { * overridden by the config * @param jmxNamePrefix Prefix to be used for JMX name for the new pool */ - public BaseGenericObjectPool(final BaseObjectPoolConfig config, + public BaseGenericObjectPool(final BaseObjectPoolConfig config, final String jmxNameBase, final String jmxNamePrefix) { if (config.getJmxEnabled()) { - this.objectName = jmxRegister(config, jmxNameBase, jmxNamePrefix); + this.oname = jmxRegister(config, jmxNameBase, jmxNamePrefix); } else { - this.objectName = null; + this.oname = null; } // Populate the creation stack trace @@ -151,7 +147,7 @@ public abstract class BaseGenericObjectPool extends BaseObject { if (cl == null) { factoryClassLoader = null; } else { - factoryClassLoader = new WeakReference<>(cl); + factoryClassLoader = new WeakReference(cl); } fairness = config.getFairness(); @@ -189,11 +185,11 @@ public abstract class BaseGenericObjectPool extends BaseObject { } /** - * Returns whether to block when the {@code borrowObject()} method is + * Returns whether to block when the borrowObject() method is * invoked when the pool is exhausted (the maximum number of "active" * objects has been reached). * - * @return {@code true} if {@code borrowObject()} should block + * @return true if borrowObject() should block * when the pool is exhausted * * @see #setBlockWhenExhausted @@ -203,12 +199,12 @@ public abstract class BaseGenericObjectPool extends BaseObject { } /** - * Sets whether to block when the {@code borrowObject()} method is + * Sets whether to block when the borrowObject() method is * invoked when the pool is exhausted (the maximum number of "active" * objects has been reached). * - * @param blockWhenExhausted {@code true} if - * {@code borrowObject()} should block + * @param blockWhenExhausted true if + * borrowObject() should block * when the pool is exhausted * * @see #getBlockWhenExhausted @@ -217,42 +213,14 @@ public abstract class BaseGenericObjectPool extends BaseObject { this.blockWhenExhausted = blockWhenExhausted; } - /** - * Initializes the receiver with the given configuration. - * - * @param config Initialization source. - */ - protected void setConfig(final BaseObjectPoolConfig config) { - setLifo(config.getLifo()); - setMaxWaitMillis(config.getMaxWaitMillis()); - setBlockWhenExhausted(config.getBlockWhenExhausted()); - setTestOnCreate(config.getTestOnCreate()); - setTestOnBorrow(config.getTestOnBorrow()); - setTestOnReturn(config.getTestOnReturn()); - setTestWhileIdle(config.getTestWhileIdle()); - setNumTestsPerEvictionRun(config.getNumTestsPerEvictionRun()); - setMinEvictableIdleTimeMillis(config.getMinEvictableIdleTimeMillis()); - setTimeBetweenEvictionRunsMillis(config.getTimeBetweenEvictionRunsMillis()); - setSoftMinEvictableIdleTimeMillis(config.getSoftMinEvictableIdleTimeMillis()); - final EvictionPolicy policy = config.getEvictionPolicy(); - if (policy == null) { - // Use the class name (pre-2.6.0 compatible) - setEvictionPolicyClassName(config.getEvictionPolicyClassName()); - } else { - // Otherwise, use the class (2.6.0 feature) - setEvictionPolicy(policy); - } - setEvictorShutdownTimeoutMillis(config.getEvictorShutdownTimeoutMillis()); - } - /** * Returns the maximum amount of time (in milliseconds) the - * {@code borrowObject()} method should block before throwing an + * borrowObject() method should block before throwing an * exception when the pool is exhausted and * {@link #getBlockWhenExhausted} is true. When less than 0, the - * {@code borrowObject()} method may block indefinitely. + * borrowObject() method may block indefinitely. * - * @return the maximum number of milliseconds {@code borrowObject()} + * @return the maximum number of milliseconds borrowObject() * will block. * * @see #setMaxWaitMillis @@ -264,13 +232,13 @@ public abstract class BaseGenericObjectPool extends BaseObject { /** * Sets the maximum amount of time (in milliseconds) the - * {@code borrowObject()} method should block before throwing an + * borrowObject() method should block before throwing an * exception when the pool is exhausted and * {@link #getBlockWhenExhausted} is true. When less than 0, the - * {@code borrowObject()} method may block indefinitely. + * borrowObject() method may block indefinitely. * * @param maxWaitMillis the maximum number of milliseconds - * {@code borrowObject()} will block or negative + * borrowObject() will block or negative * for indefinitely. * * @see #getMaxWaitMillis @@ -281,14 +249,14 @@ public abstract class BaseGenericObjectPool extends BaseObject { } /** - * Returns whether the pool has LIFO (last in, first out) behavior with + * Returns whether the pool has LIFO (last in, first out) behaviour with * respect to idle objects - always returning the most recently used object * from the pool, or as a FIFO (first in, first out) queue, where the pool * always returns the oldest object in the idle object pool. * - * @return {@code true} if the pool is configured with LIFO behavior - * or {@code false} if the pool is configured with FIFO - * behavior + * @return true if the pool is configured with LIFO behaviour + * or false if the pool is configured with FIFO + * behaviour * * @see #setLifo */ @@ -300,7 +268,7 @@ public abstract class BaseGenericObjectPool extends BaseObject { * Returns whether or not the pool serves threads waiting to borrow objects fairly. * True means that waiting threads are served as if waiting in a FIFO queue. * - * @return {@code true} if waiting threads are to be served + * @return true if waiting threads are to be served * by the pool in arrival order */ public final boolean getFairness() { @@ -308,14 +276,14 @@ public abstract class BaseGenericObjectPool extends BaseObject { } /** - * Sets whether the pool has LIFO (last in, first out) behavior with + * Sets whether the pool has LIFO (last in, first out) behaviour with * respect to idle objects - always returning the most recently used object * from the pool, or as a FIFO (first in, first out) queue, where the pool * always returns the oldest object in the idle object pool. * - * @param lifo {@code true} if the pool is to be configured with LIFO - * behavior or {@code false} if the pool is to be - * configured with FIFO behavior + * @param lifo true if the pool is to be configured with LIFO + * behaviour or false if the pool is to be + * configured with FIFO behaviour * * @see #getLifo() */ @@ -325,13 +293,13 @@ public abstract class BaseGenericObjectPool extends BaseObject { /** * Returns whether objects created for the pool will be validated before - * being returned from the {@code borrowObject()} method. Validation is - * performed by the {@code validateObject()} method of the factory + * being returned from the borrowObject() method. Validation is + * performed by the validateObject() method of the factory * associated with the pool. If the object fails to validate, then - * {@code borrowObject()} will fail. + * borrowObject() will fail. * - * @return {@code true} if newly created objects are validated before - * being returned from the {@code borrowObject()} method + * @return true if newly created objects are validated before + * being returned from the borrowObject() method * * @see #setTestOnCreate * @@ -343,14 +311,14 @@ public abstract class BaseGenericObjectPool extends BaseObject { /** * Sets whether objects created for the pool will be validated before - * being returned from the {@code borrowObject()} method. Validation is - * performed by the {@code validateObject()} method of the factory + * being returned from the borrowObject() method. Validation is + * performed by the validateObject() method of the factory * associated with the pool. If the object fails to validate, then - * {@code borrowObject()} will fail. + * borrowObject() will fail. * - * @param testOnCreate {@code true} if newly created objects should be + * @param testOnCreate true if newly created objects should be * validated before being returned from the - * {@code borrowObject()} method + * borrowObject() method * * @see #getTestOnCreate * @@ -362,14 +330,14 @@ public abstract class BaseGenericObjectPool extends BaseObject { /** * Returns whether objects borrowed from the pool will be validated before - * being returned from the {@code borrowObject()} method. Validation is - * performed by the {@code validateObject()} method of the factory + * being returned from the borrowObject() method. Validation is + * performed by the validateObject() method of the factory * associated with the pool. If the object fails to validate, it will be * removed from the pool and destroyed, and a new attempt will be made to * borrow an object from the pool. * - * @return {@code true} if objects are validated before being returned - * from the {@code borrowObject()} method + * @return true if objects are validated before being returned + * from the borrowObject() method * * @see #setTestOnBorrow */ @@ -379,15 +347,15 @@ public abstract class BaseGenericObjectPool extends BaseObject { /** * Sets whether objects borrowed from the pool will be validated before - * being returned from the {@code borrowObject()} method. Validation is - * performed by the {@code validateObject()} method of the factory + * being returned from the borrowObject() method. Validation is + * performed by the validateObject() method of the factory * associated with the pool. If the object fails to validate, it will be * removed from the pool and destroyed, and a new attempt will be made to * borrow an object from the pool. * - * @param testOnBorrow {@code true} if objects should be validated + * @param testOnBorrow true if objects should be validated * before being returned from the - * {@code borrowObject()} method + * borrowObject() method * * @see #getTestOnBorrow */ @@ -397,13 +365,13 @@ public abstract class BaseGenericObjectPool extends BaseObject { /** * Returns whether objects borrowed from the pool will be validated when - * they are returned to the pool via the {@code returnObject()} method. - * Validation is performed by the {@code validateObject()} method of + * they are returned to the pool via the returnObject() method. + * Validation is performed by the validateObject() method of * the factory associated with the pool. Returning objects that fail validation * are destroyed rather then being returned the pool. * - * @return {@code true} if objects are validated on return to - * the pool via the {@code returnObject()} method + * @return true if objects are validated on return to + * the pool via the returnObject() method * * @see #setTestOnReturn */ @@ -413,14 +381,14 @@ public abstract class BaseGenericObjectPool extends BaseObject { /** * Sets whether objects borrowed from the pool will be validated when - * they are returned to the pool via the {@code returnObject()} method. - * Validation is performed by the {@code validateObject()} method of + * they are returned to the pool via the returnObject() method. + * Validation is performed by the validateObject() method of * the factory associated with the pool. Returning objects that fail validation * are destroyed rather then being returned the pool. * - * @param testOnReturn {@code true} if objects are validated on + * @param testOnReturn true if objects are validated on * return to the pool via the - * {@code returnObject()} method + * returnObject() method * * @see #getTestOnReturn */ @@ -432,11 +400,11 @@ public abstract class BaseGenericObjectPool extends BaseObject { * Returns whether objects sitting idle in the pool will be validated by the * idle object evictor (if any - see * {@link #setTimeBetweenEvictionRunsMillis(long)}). Validation is performed - * by the {@code validateObject()} method of the factory associated + * by the validateObject() method of the factory associated * with the pool. If the object fails to validate, it will be removed from * the pool and destroyed. * - * @return {@code true} if objects will be validated by the evictor + * @return true if objects will be validated by the evictor * * @see #setTestWhileIdle * @see #setTimeBetweenEvictionRunsMillis @@ -449,14 +417,14 @@ public abstract class BaseGenericObjectPool extends BaseObject { * Returns whether objects sitting idle in the pool will be validated by the * idle object evictor (if any - see * {@link #setTimeBetweenEvictionRunsMillis(long)}). Validation is performed - * by the {@code validateObject()} method of the factory associated + * by the validateObject() method of the factory associated * with the pool. If the object fails to validate, it will be removed from * the pool and destroyed. Note that setting this property has no effect * unless the idle object evictor is enabled by setting - * {@code timeBetweenEvictionRunsMillis} to a positive value. + * timeBetweenEvictionRunsMillis to a positive value. * * @param testWhileIdle - * {@code true} so objects will be validated by the evictor + * true so objects will be validated by the evictor * * @see #getTestWhileIdle * @see #setTimeBetweenEvictionRunsMillis @@ -479,11 +447,9 @@ public abstract class BaseGenericObjectPool extends BaseObject { } /** - * Sets the number of milliseconds to sleep between runs of the idle object evictor thread. - *
      - *
    • When positive, the idle object evictor thread starts.
    • - *
    • When non-positive, no idle object evictor thread runs.
    • - *
    + * Sets the number of milliseconds to sleep between runs of the idle + * object evictor thread. When non-positive, no idle object evictor thread + * will be run. * * @param timeBetweenEvictionRunsMillis * number of milliseconds to sleep between evictor runs @@ -503,7 +469,7 @@ public abstract class BaseGenericObjectPool extends BaseObject { * number of idle instances in the pool. When negative, the number of tests * performed will be ceil({@link #getNumIdle}/ * abs({@link #getNumTestsPerEvictionRun})) which means that when the - * value is {@code -n} roughly one nth of the idle objects will be + * value is -n roughly one nth of the idle objects will be * tested per run. * * @return max number of objects to examine during each evictor run @@ -522,7 +488,7 @@ public abstract class BaseGenericObjectPool extends BaseObject { * number of idle instances in the pool. When negative, the number of tests * performed will be ceil({@link #getNumIdle}/ * abs({@link #getNumTestsPerEvictionRun})) which means that when the - * value is {@code -n} roughly one nth of the idle objects will be + * value is -n roughly one nth of the idle objects will be * tested per run. * * @param numTestsPerEvictionRun @@ -573,7 +539,7 @@ public abstract class BaseGenericObjectPool extends BaseObject { * Returns the minimum amount of time an object may sit idle in the pool * before it is eligible for eviction by the idle object evictor (if any - * see {@link #setTimeBetweenEvictionRunsMillis(long)}), - * with the extra condition that at least {@code minIdle} object + * with the extra condition that at least minIdle object * instances remain in the pool. This setting is overridden by * {@link #getMinEvictableIdleTimeMillis} (that is, if * {@link #getMinEvictableIdleTimeMillis} is positive, then @@ -592,7 +558,7 @@ public abstract class BaseGenericObjectPool extends BaseObject { * Sets the minimum amount of time an object may sit idle in the pool * before it is eligible for eviction by the idle object evictor (if any - * see {@link #setTimeBetweenEvictionRunsMillis(long)}), - * with the extra condition that at least {@code minIdle} object + * with the extra condition that at least minIdle object * instances remain in the pool. This setting is overridden by * {@link #getMinEvictableIdleTimeMillis} (that is, if * {@link #getMinEvictableIdleTimeMillis} is positive, then @@ -623,81 +589,59 @@ public abstract class BaseGenericObjectPool extends BaseObject { } /** - * Sets the eviction policy for this pool. + * Sets the name of the {@link EvictionPolicy} implementation that is + * used by this pool. The Pool will attempt to load the class using the + * thread context class loader. If that fails, the Pool will attempt to load + * the class using the class loader that loaded this class. * - * @param evictionPolicy - * the eviction policy for this pool. - * @since 2.6.0 - */ - public void setEvictionPolicy(final EvictionPolicy evictionPolicy) { - this.evictionPolicy = evictionPolicy; - } - - /** - * Sets the name of the {@link EvictionPolicy} implementation that is used by this pool. The Pool will attempt to - * load the class using the given class loader. If that fails, use the class loader for the {@link EvictionPolicy} - * interface. - * - * @param evictionPolicyClassName - * the fully qualified class name of the new eviction policy - * @param classLoader - * the class loader to load the given {@code evictionPolicyClassName}. + * @param evictionPolicyClassName the fully qualified class name of the + * new eviction policy * * @see #getEvictionPolicyClassName() - * @since 2.6.0 If loading the class using the given class loader fails, use the class loader for the - * {@link EvictionPolicy} interface. */ - public final void setEvictionPolicyClassName(final String evictionPolicyClassName, final ClassLoader classLoader) { - // Getting epClass here and now best matches the caller's environment - final Class epClass = EvictionPolicy.class; - final ClassLoader epClassLoader = epClass.getClassLoader(); + public final void setEvictionPolicyClassName( + final String evictionPolicyClassName) { try { + Class clazz; try { - setEvictionPolicy(evictionPolicyClassName, classLoader); - } catch (final ClassCastException | ClassNotFoundException e) { - setEvictionPolicy(evictionPolicyClassName, epClassLoader); + clazz = Class.forName(evictionPolicyClassName, true, + Thread.currentThread().getContextClassLoader()); + } catch (final ClassNotFoundException e) { + clazz = Class.forName(evictionPolicyClassName); + } + final Object policy = clazz.getConstructor().newInstance(); + if (policy instanceof EvictionPolicy) { + @SuppressWarnings("unchecked") // safe, because we just checked the class + final + EvictionPolicy evicPolicy = (EvictionPolicy) policy; + this.evictionPolicy = evicPolicy; + } else { + throw new IllegalArgumentException("[" + evictionPolicyClassName + + "] does not implement EvictionPolicy"); } - } catch (final ClassCastException e) { - throw new IllegalArgumentException("Class " + evictionPolicyClassName + " from class loaders [" + - classLoader + ", " + epClassLoader + "] do not implement " + EVICTION_POLICY_TYPE_NAME); - } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException | - InvocationTargetException | NoSuchMethodException e) { - final String exMessage = "Unable to create " + EVICTION_POLICY_TYPE_NAME + " instance of type " + - evictionPolicyClassName; - throw new IllegalArgumentException(exMessage, e); + } catch (final ClassNotFoundException e) { + throw new IllegalArgumentException( + "Unable to create EvictionPolicy instance of type " + + evictionPolicyClassName, e); + } catch (final InstantiationException e) { + throw new IllegalArgumentException( + "Unable to create EvictionPolicy instance of type " + + evictionPolicyClassName, e); + } catch (final IllegalAccessException e) { + throw new IllegalArgumentException( + "Unable to create EvictionPolicy instance of type " + + evictionPolicyClassName, e); + } catch (final InvocationTargetException e) { + throw new IllegalArgumentException( + "Unable to create EvictionPolicy instance of type " + + evictionPolicyClassName, e); + } catch (final NoSuchMethodException e) { + throw new IllegalArgumentException( + "Unable to create EvictionPolicy instance of type " + + evictionPolicyClassName, e); } } - /** - * Sets the eviction policy. - * - * @param className Eviction policy class name. - * @param classLoader Load the class from this class loader. - */ - @SuppressWarnings("unchecked") - private void setEvictionPolicy(final String className, final ClassLoader classLoader) - throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { - final Class clazz = Class.forName(className, true, classLoader); - final Object policy = clazz.getConstructor().newInstance(); - this.evictionPolicy = (EvictionPolicy) policy; - } - - /** - * Sets the name of the {@link EvictionPolicy} implementation that is used by this pool. The Pool will attempt to - * load the class using the thread context class loader. If that fails, the use the class loader for the - * {@link EvictionPolicy} interface. - * - * @param evictionPolicyClassName - * the fully qualified class name of the new eviction policy - * - * @see #getEvictionPolicyClassName() - * @since 2.6.0 If loading the class using the thread context class loader fails, use the class loader for the - * {@link EvictionPolicy} interface. - */ - public final void setEvictionPolicyClassName(final String evictionPolicyClassName) { - setEvictionPolicyClassName(evictionPolicyClassName, Thread.currentThread().getContextClassLoader()); - } - /** * Gets the timeout that will be used when waiting for the Evictor to * shutdown if this pool is closed and it is the only pool still using the @@ -732,18 +676,18 @@ public abstract class BaseGenericObjectPool extends BaseObject { /** * Has this pool instance been closed. - * @return {@code true} when this pool has been closed. + * @return true when this pool has been closed. */ public final boolean isClosed() { return closed; } /** - *

    Perform {@code numTests} idle object eviction tests, evicting + *

    Perform numTests idle object eviction tests, evicting * examined objects that meet the criteria for eviction. If - * {@code testWhileIdle} is true, examined objects are validated + * testWhileIdle is true, examined objects are validated * when visited (and removed if invalid); otherwise only objects that - * have been idle for more than {@code minEvicableIdleTimeMillis} + * have been idle for more than minEvicableIdleTimeMillis * are removed.

    * * @throws Exception when there is a problem evicting idle objects. @@ -755,9 +699,8 @@ public abstract class BaseGenericObjectPool extends BaseObject { * * @return the eviction policy * @since 2.4 - * @since 2.6.0 Changed access from protected to public. */ - public EvictionPolicy getEvictionPolicy() { + protected EvictionPolicy getEvictionPolicy() { return evictionPolicy; } @@ -783,33 +726,18 @@ public abstract class BaseGenericObjectPool extends BaseObject { */ final void startEvictor(final long delay) { synchronized (evictionLock) { - if (evictor == null) { // Starting evictor for the first time or after a cancel - if (delay > 0) { // Starting new evictor - evictor = new Evictor(); - EvictionTimer.schedule(evictor, delay, delay); - } - } else { // Stop or restart of existing evictor - if (delay > 0) { // Restart - synchronized (EvictionTimer.class) { // Ensure no cancel can happen between cancel / schedule calls - EvictionTimer.cancel(evictor, evictorShutdownTimeoutMillis, TimeUnit.MILLISECONDS, true); - evictor = null; - evictionIterator = null; - evictor = new Evictor(); - EvictionTimer.schedule(evictor, delay, delay); - } - } else { // Stopping evictor - EvictionTimer.cancel(evictor, evictorShutdownTimeoutMillis, TimeUnit.MILLISECONDS, false); - } + if (null != evictor) { + EvictionTimer.cancel(evictor, evictorShutdownTimeoutMillis, TimeUnit.MILLISECONDS); + evictor = null; + evictionIterator = null; + } + if (delay > 0) { + evictor = new Evictor(); + EvictionTimer.schedule(evictor, delay, delay); } } } - /** - * Stops the evictor. - */ - void stopEvictor() { - startEvictor(-1L); - } /** * Tries to ensure that the configured minimum number of idle instances are * available in the pool. @@ -822,12 +750,12 @@ public abstract class BaseGenericObjectPool extends BaseObject { /** * Provides the name under which the pool has been registered with the - * platform MBean server or {@code null} if the pool has not been + * platform MBean server or null if the pool has not been * registered. * @return the JMX name */ public final ObjectName getJmxName() { - return objectName; + return oname; } /** @@ -890,7 +818,7 @@ public abstract class BaseGenericObjectPool extends BaseObject { /** * The total number of objects destroyed by this pool as a result of failing - * validation during {@code borrowObject()} over the lifetime of the + * validation during borrowObject() over the lifetime of the * pool. * @return validation destroyed object count */ @@ -946,7 +874,7 @@ public abstract class BaseGenericObjectPool extends BaseObject { * The listener used (if any) to receive notifications of exceptions * unavoidably swallowed by the pool. * - * @return The listener or {@code null} for no listener + * @return The listener or null for no listener */ public final SwallowedExceptionListener getSwallowedExceptionListener() { return swallowedExceptionListener; @@ -956,7 +884,7 @@ public abstract class BaseGenericObjectPool extends BaseObject { * The listener used (if any) to receive notifications of exceptions * unavoidably swallowed by the pool. * - * @param swallowedExceptionListener The listener or {@code null} + * @param swallowedExceptionListener The listener or null * for no listener */ public final void setSwallowedExceptionListener( @@ -968,9 +896,9 @@ public abstract class BaseGenericObjectPool extends BaseObject { * Swallows an exception and notifies the configured listener for swallowed * exceptions queue. * - * @param swallowException exception to be swallowed + * @param e exception to be swallowed */ - final void swallowException(final Exception swallowException) { + final void swallowException(final Exception e) { final SwallowedExceptionListener listener = getSwallowedExceptionListener(); if (listener == null) { @@ -978,9 +906,11 @@ public abstract class BaseGenericObjectPool extends BaseObject { } try { - listener.onSwallowException(swallowException); - } catch (final VirtualMachineError e) { - throw e; + listener.onSwallowException(e); + } catch (final OutOfMemoryError oome) { + throw oome; + } catch (final VirtualMachineError vme) { + throw vme; } catch (final Throwable t) { // Ignore. Enjoy the irony. } @@ -1016,30 +946,17 @@ public abstract class BaseGenericObjectPool extends BaseObject { activeTimes.add(activeTime); } - /** - * Marks the object as returning to the pool. - * @param pooledObject instance to return to the keyed pool - */ - protected void markReturningState(final PooledObject pooledObject) { - synchronized(pooledObject) { - final PooledObjectState state = pooledObject.getState(); - if (state != PooledObjectState.ALLOCATED) { - throw new IllegalStateException( - "Object has already been returned to this pool or is invalid"); - } - pooledObject.markReturning(); // Keep from being marked abandoned - } - } - /** * Unregisters this pool's MBean. */ final void jmxUnregister() { - if (objectName != null) { + if (oname != null) { try { ManagementFactory.getPlatformMBeanServer().unregisterMBean( - objectName); - } catch (final MBeanRegistrationException | InstanceNotFoundException e) { + oname); + } catch (final MBeanRegistrationException e) { + swallowException(e); + } catch (final InstanceNotFoundException e) { swallowException(e); } } @@ -1048,7 +965,7 @@ public abstract class BaseGenericObjectPool extends BaseObject { /** * Registers the pool with the platform MBean server. * The registered name will be - * {@code jmxNameBase + jmxNamePrefix + i} where i is the least + * jmxNameBase + jmxNamePrefix + i where i is the least * integer greater than or equal to 1 such that the name is not already * registered. Swallows MBeanRegistrationException, NotCompliantMBeanException * returning null. @@ -1058,9 +975,9 @@ public abstract class BaseGenericObjectPool extends BaseObject { * @param jmxNamePrefix name prefix * @return registered ObjectName, null if registration fails */ - private ObjectName jmxRegister(final BaseObjectPoolConfig config, + private ObjectName jmxRegister(final BaseObjectPoolConfig config, final String jmxNameBase, String jmxNamePrefix) { - ObjectName newObjectName = null; + ObjectName objectName = null; final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); int i = 1; boolean registered = false; @@ -1079,7 +996,7 @@ public abstract class BaseGenericObjectPool extends BaseObject { objName = new ObjectName(base + jmxNamePrefix + i); } mbs.registerMBean(this, objName); - newObjectName = objName; + objectName = objName; registered = true; } catch (final MalformedObjectNameException e) { if (BaseObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX.equals( @@ -1095,12 +1012,15 @@ public abstract class BaseGenericObjectPool extends BaseObject { } catch (final InstanceAlreadyExistsException e) { // Increment the index and try again i++; - } catch (final MBeanRegistrationException | NotCompliantMBeanException e) { + } catch (final MBeanRegistrationException e) { + // Shouldn't happen. Skip registration if it does. + registered = true; + } catch (final NotCompliantMBeanException e) { // Shouldn't happen. Skip registration if it does. registered = true; } } - return newObjectName; + return objectName; } /** @@ -1125,10 +1045,7 @@ public abstract class BaseGenericObjectPool extends BaseObject { * * @see GenericKeyedObjectPool#setTimeBetweenEvictionRunsMillis */ - class Evictor implements Runnable { - - private ScheduledFuture scheduledFuture; - + class Evictor extends TimerTask { /** * Run pool maintenance. Evict objects qualifying for eviction and then * ensure that the minimum number of idle instances are available. @@ -1176,25 +1093,6 @@ public abstract class BaseGenericObjectPool extends BaseObject { Thread.currentThread().setContextClassLoader(savedClassLoader); } } - - - /** - * Sets the scheduled future. - * - * @param scheduledFuture the scheduled future. - */ - void setScheduledFuture(final ScheduledFuture scheduledFuture) { - this.scheduledFuture = scheduledFuture; - } - - - /** - * Cancels the scheduled future. - */ - void cancel() { - scheduledFuture.cancel(false); - } - } /** @@ -1411,7 +1309,7 @@ public abstract class BaseGenericObjectPool extends BaseObject { builder.append(", factoryClassLoader="); builder.append(factoryClassLoader); builder.append(", oname="); - builder.append(objectName); + builder.append(oname); builder.append(", creationStackTrace="); builder.append(creationStackTrace); builder.append(", borrowedCount="); @@ -1438,5 +1336,4 @@ public abstract class BaseGenericObjectPool extends BaseObject { builder.append(swallowedExceptionListener); } - } diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/BaseObjectPoolConfig.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/BaseObjectPoolConfig.java index 0f6a7418d..f54c51456 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/BaseObjectPoolConfig.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/BaseObjectPoolConfig.java @@ -24,12 +24,10 @@ import com.fr.third.org.apache.commons.pool2.BaseObject; * defined by the public constants. *

    * This class is not thread-safe. - *

    * - * @param Type of element pooled. * @since 2.0 */ -public abstract class BaseObjectPoolConfig extends BaseObject implements Cloneable { +public abstract class BaseObjectPoolConfig extends BaseObject implements Cloneable { /** * The default value for the {@code lifo} configuration attribute. @@ -148,7 +146,7 @@ public abstract class BaseObjectPoolConfig extends BaseObject implements Clon /** * The default value for the base name to use to name JMX enabled pools - * created with a configuration instance. The default is {@code null} + * created with a configuration instance. The default is null * which means the pool will provide the base name to use. * @see GenericObjectPool#getJmxName() * @see GenericKeyedObjectPool#getJmxName() @@ -161,7 +159,9 @@ public abstract class BaseObjectPoolConfig extends BaseObject implements Clon * @see GenericObjectPool#getEvictionPolicyClassName() * @see GenericKeyedObjectPool#getEvictionPolicyClassName() */ - public static final String DEFAULT_EVICTION_POLICY_CLASS_NAME = DefaultEvictionPolicy.class.getName(); + public static final String DEFAULT_EVICTION_POLICY_CLASS_NAME = + "com.fr.third.org.apache.commons.pool2.impl.DefaultEvictionPolicy"; + private boolean lifo = DEFAULT_LIFO; @@ -181,8 +181,6 @@ public abstract class BaseObjectPoolConfig extends BaseObject implements Clon private int numTestsPerEvictionRun = DEFAULT_NUM_TESTS_PER_EVICTION_RUN; - private EvictionPolicy evictionPolicy = null; // Only 2.6.0 applications set this - private String evictionPolicyClassName = DEFAULT_EVICTION_POLICY_CLASS_NAME; private boolean testOnCreate = DEFAULT_TEST_ON_CREATE; @@ -554,21 +552,6 @@ public abstract class BaseObjectPoolConfig extends BaseObject implements Clon this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; } - /** - * Get the value for the {@code evictionPolicyClass} configuration - * attribute for pools created with this configuration instance. - * - * @return The current setting of {@code evictionPolicyClass} for this - * configuration instance - * - * @see GenericObjectPool#getEvictionPolicy() - * @see GenericKeyedObjectPool#getEvictionPolicy() - * @since 2.6.0 - */ - public EvictionPolicy getEvictionPolicy() { - return evictionPolicy; - } - /** * Get the value for the {@code evictionPolicyClassName} configuration * attribute for pools created with this configuration instance. @@ -583,21 +566,6 @@ public abstract class BaseObjectPoolConfig extends BaseObject implements Clon return evictionPolicyClassName; } - /** - * Set the value for the {@code evictionPolicyClass} configuration - * attribute for pools created with this configuration instance. - * - * @param evictionPolicy The new setting of - * {@code evictionPolicyClass} for this configuration instance - * - * @see GenericObjectPool#getEvictionPolicy() - * @see GenericKeyedObjectPool#getEvictionPolicy() - * @since 2.6.0 - */ - public void setEvictionPolicy(final EvictionPolicy evictionPolicy) { - this.evictionPolicy = evictionPolicy; - } - /** * Set the value for the {@code evictionPolicyClassName} configuration * attribute for pools created with this configuration instance. @@ -665,7 +633,7 @@ public abstract class BaseObjectPoolConfig extends BaseObject implements Clon /** * Gets the value of the JMX name base that will be used as part of the * name assigned to JMX enabled pools created with this configuration - * instance. A value of {@code null} means that the pool will define + * instance. A value of null means that the pool will define * the JMX name base. * * @return The current setting of {@code jmxNameBase} for this @@ -678,7 +646,7 @@ public abstract class BaseObjectPoolConfig extends BaseObject implements Clon /** * Sets the value of the JMX name base that will be used as part of the * name assigned to JMX enabled pools created with this configuration - * instance. A value of {@code null} means that the pool will define + * instance. A value of null means that the pool will define * the JMX name base. * * @param jmxNameBase The new setting of {@code jmxNameBase} diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/CallStackUtils.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/CallStackUtils.java index 686dad881..e223fb745 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/CallStackUtils.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/CallStackUtils.java @@ -25,9 +25,13 @@ import java.security.AccessControlException; */ public final class CallStackUtils { + private static final boolean CAN_CREATE_SECURITY_MANAGER; + + static { + CAN_CREATE_SECURITY_MANAGER = canCreateSecurityManager(); + } + /** - * Returns whether the caller can create a security manager in the current environment. - * * @return {@code true} if it is able to create a security manager in the current environment, {@code false} * otherwise. */ @@ -72,9 +76,9 @@ public final class CallStackUtils { public static CallStack newCallStack(final String messageFormat, final boolean useTimestamp, final boolean requireFullStackTrace) { - return canCreateSecurityManager() && !requireFullStackTrace ? - new SecurityManagerCallStack(messageFormat, useTimestamp) : - new ThrowableCallStack(messageFormat, useTimestamp); + return CAN_CREATE_SECURITY_MANAGER && !requireFullStackTrace + ? new SecurityManagerCallStack(messageFormat, useTimestamp) + : new ThrowableCallStack(messageFormat, useTimestamp); } /** diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultEvictionPolicy.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultEvictionPolicy.java index 5be188f8c..ad5afc601 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultEvictionPolicy.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultEvictionPolicy.java @@ -31,9 +31,7 @@ import com.fr.third.org.apache.commons.pool2.PooledObject; * {@link GenericObjectPool#getSoftMinEvictableIdleTimeMillis()} / * {@link GenericKeyedObjectPool#getSoftMinEvictableIdleTimeMillis()} * - *

    * This class is immutable and thread-safe. - *

    * * @param the type of objects in the pool * diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultPooledObject.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultPooledObject.java index 740bff894..c7dd093ec 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultPooledObject.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultPooledObject.java @@ -28,7 +28,6 @@ import java.util.Deque; * the pooled objects. *

    * This class is intended to be thread-safe. - *

    * * @param the type of object in the pool * @@ -48,7 +47,7 @@ public class DefaultPooledObject implements PooledObject { private volatile long borrowedCount = 0; /** - * Creates a new instance that wraps the provided object so that the pool can + * Create a new instance that wraps the provided object so that the pool can * track the state of the pooled object. * * @param object The object to wrap @@ -82,10 +81,10 @@ public class DefaultPooledObject implements PooledObject { @Override public long getIdleTimeMillis() { final long elapsed = System.currentTimeMillis() - lastReturnTime; - // elapsed may be negative if: - // - another thread updates lastReturnTime during the calculation window - // - System.currentTimeMillis() is not monotonic (e.g. system time is set back) - return elapsed >= 0 ? elapsed : 0; + // elapsed may be negative if: + // - another thread updates lastReturnTime during the calculation window + // - System.currentTimeMillis() is not monotonic (e.g. system time is set back) + return elapsed >= 0 ? elapsed : 0; } @Override @@ -99,17 +98,16 @@ public class DefaultPooledObject implements PooledObject { } /** - * Gets the number of times this object has been borrowed. + * Get the number of times this object has been borrowed. * @return The number of times this object has been borrowed. * @since 2.1 */ - @Override public long getBorrowedCount() { return borrowedCount; } /** - * Returns an estimate of the last time this object was used. If the class + * Return an estimate of the last time this object was used. If the class * of the pooled object implements {@link TrackedUse}, what is returned is * the maximum of {@link TrackedUse#getLastUsed()} and * {@link #getLastBorrowTime()}; otherwise this method gives the same @@ -206,11 +204,9 @@ public class DefaultPooledObject implements PooledObject { /** * Deallocates the object and sets it {@link PooledObjectState#IDLE IDLE} - * if it is currently {@link PooledObjectState#ALLOCATED ALLOCATED} - * or {@link PooledObjectState#RETURNING RETURNING}. + * if it is currently {@link PooledObjectState#ALLOCATED ALLOCATED}. * * @return {@code true} if the state was {@link PooledObjectState#ALLOCATED ALLOCATED} - * or {@link PooledObjectState#RETURNING RETURNING}. */ @Override public synchronized boolean deallocate() { @@ -288,7 +284,8 @@ public class DefaultPooledObject implements PooledObject { * logging * @since 2.5 */ - @Override + // TODO: uncomment below in 3.0 + // @Override public void setRequireFullStackTrace(final boolean requireFullStackTrace) { borrowedBy = CallStackUtils.newCallStack("'Pooled object created' " + "yyyy-MM-dd HH:mm:ss Z 'by the following code has not been returned to the pool:'", diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultPooledObjectInfo.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultPooledObjectInfo.java index da38f7eb8..3dd860fce 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultPooledObjectInfo.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultPooledObjectInfo.java @@ -93,7 +93,11 @@ public class DefaultPooledObjectInfo implements DefaultPooledObjectInfoMBean { @Override public long getBorrowedCount() { - return pooledObject.getBorrowedCount(); + // TODO Simplify this once getBorrowedCount has been added to PooledObject + if (pooledObject instanceof DefaultPooledObject) { + return ((DefaultPooledObject) pooledObject).getBorrowedCount(); + } + return -1; } /** diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultPooledObjectInfoMBean.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultPooledObjectInfoMBean.java index 2259072a3..13d17236a 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultPooledObjectInfoMBean.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultPooledObjectInfoMBean.java @@ -42,7 +42,7 @@ public interface DefaultPooledObjectInfoMBean { * Obtain the time that pooled object was created. * * @return The creation time for the pooled object formatted as - * {@code yyyy-MM-dd HH:mm:ss Z} + * yyyy-MM-dd HH:mm:ss Z */ String getCreateTimeFormatted(); @@ -57,8 +57,8 @@ public interface DefaultPooledObjectInfoMBean { /** * Obtain the time that pooled object was last borrowed. * - * @return The last borrowed time for the pooled object formatted as - * {@code yyyy-MM-dd HH:mm:ss Z} + * @return The last borrowed time for the pooled object formated as + * yyyy-MM-dd HH:mm:ss Z */ String getLastBorrowTimeFormatted(); @@ -82,8 +82,8 @@ public interface DefaultPooledObjectInfoMBean { /** * Obtain the time that pooled object was last returned. * - * @return The last returned time for the pooled object formatted as - * {@code yyyy-MM-dd HH:mm:ss Z} + * @return The last returned time for the pooled object formated as + * yyyy-MM-dd HH:mm:ss Z */ String getLastReturnTimeFormatted(); diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionConfig.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionConfig.java index c40619584..a4cac4df8 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionConfig.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionConfig.java @@ -22,7 +22,6 @@ package com.fr.third.org.apache.commons.pool2.impl; * its own specific configuration attributes. *

    * This class is immutable and thread-safe. - *

    * * @since 2.0 */ diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionPolicy.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionPolicy.java index 0be30e47b..c2ea2132d 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionPolicy.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionPolicy.java @@ -37,8 +37,9 @@ public interface EvictionPolicy { * @param underTest The pooled object being tested for eviction * @param idleCount The current number of idle objects in the pool including * the object under test - * @return {@code true} if the object should be evicted, otherwise - * {@code false} + * @return true if the object should be evicted, otherwise + * false */ - boolean evict(EvictionConfig config, PooledObject underTest, int idleCount); + boolean evict(EvictionConfig config, PooledObject underTest, + int idleCount); } diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionTimer.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionTimer.java index 444d588ef..5a241c5d6 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionTimer.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionTimer.java @@ -16,32 +16,26 @@ */ package com.fr.third.org.apache.commons.pool2.impl; -import java.lang.ref.WeakReference; import java.security.AccessController; import java.security.PrivilegedAction; -import java.util.HashMap; -import java.util.Map.Entry; -import java.util.concurrent.ScheduledFuture; +import java.util.TimerTask; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; - /** - * Provides a shared idle object eviction timer for all pools. - *

    - * This class is currently implemented using {@link ScheduledThreadPoolExecutor}. This implementation may change in any - * future release. This class keeps track of how many pools are using it. If no pools are using the timer, it is - * cancelled. This prevents a thread being left running which, in application server environments, can lead to memory - * leads and/or prevent applications from shutting down or reloading cleanly. - *

    + * Provides a shared idle object eviction timer for all pools. This class is + * currently implemented using {@link ScheduledThreadPoolExecutor}. This + * implementation may change in any future release. This class keeps track of + * how many pools are using it. If no pools are using the timer, it is cancelled. + * This prevents a thread being left running which, in application server + * environments, can lead to memory leads and/or prevent applications from + * shutting down or reloading cleanly. *

    - * This class has package scope to prevent its inclusion in the pool public API. The class declaration below should - * *not* be changed to public. - *

    + * This class has package scope to prevent its inclusion in the pool public API. + * The class declaration below should *not* be changed to public. *

    * This class is intended to be thread-safe. - *

    * * @since 2.0 */ @@ -50,10 +44,10 @@ class EvictionTimer { /** Executor instance */ private static ScheduledThreadPoolExecutor executor; //@GuardedBy("EvictionTimer.class") - /** Keys are weak references to tasks, values are runners managed by executor. */ - private static final HashMap, WeakRunner> taskMap = new HashMap<>(); // @GuardedBy("EvictionTimer.class") + /** Static usage count tracker */ + private static int usageCount; //@GuardedBy("EvictionTimer.class") - /** Prevents instantiation */ + /** Prevent instantiation */ private EvictionTimer() { // Hide the default constructor } @@ -69,50 +63,37 @@ class EvictionTimer { return builder.toString(); } + /** - * Adds the specified eviction task to the timer. Tasks that are added with - * a call to this method *must* call {@link - * #cancel(org.apache.commons.pool2.impl.BaseGenericObjectPool.Evictor, long, TimeUnit)} - * to cancel the task to prevent memory and/or thread leaks in application - * server environments. - * - * @param task Task to be scheduled. - * @param delay Delay in milliseconds before task is executed. - * @param period Time in milliseconds between executions. + * Add the specified eviction task to the timer. Tasks that are added with a + * call to this method *must* call {@link #cancel(TimerTask)} to cancel the + * task to prevent memory and/or thread leaks in application server + * environments. + * @param task Task to be scheduled + * @param delay Delay in milliseconds before task is executed + * @param period Time in milliseconds between executions */ - static synchronized void schedule( - final BaseGenericObjectPool.Evictor task, final long delay, final long period) { + static synchronized void schedule(final Runnable task, final long delay, final long period) { if (null == executor) { executor = new ScheduledThreadPoolExecutor(1, new EvictorThreadFactory()); - executor.setRemoveOnCancelPolicy(true); - executor.scheduleAtFixedRate(new Reaper(), delay, period, TimeUnit.MILLISECONDS); } - final WeakReference ref = new WeakReference<>(task); - final WeakRunner runner = new WeakRunner(ref); - final ScheduledFuture scheduledFuture = - executor.scheduleWithFixedDelay(runner, delay, period, TimeUnit.MILLISECONDS); - task.setScheduledFuture(scheduledFuture); - taskMap.put(ref, runner); + usageCount++; + executor.scheduleWithFixedDelay(task, delay, period, TimeUnit.MILLISECONDS); } /** - * Removes the specified eviction task from the timer. + * Remove the specified eviction task from the timer. * - * @param evictor Task to be cancelled. + * @param task Task to be cancelled * @param timeout If the associated executor is no longer required, how * long should this thread wait for the executor to * terminate? - * @param unit The units for the specified timeout. - * @param restarting The state of the evictor. + * @param unit The units for the specified timeout */ - static synchronized void cancel( - final BaseGenericObjectPool.Evictor evictor, final long timeout, final TimeUnit unit, - final boolean restarting) { - if (evictor != null) { - evictor.cancel(); - remove(evictor); - } - if (!restarting && executor != null && taskMap.isEmpty()) { + static synchronized void cancel(final TimerTask task, final long timeout, final TimeUnit unit) { + task.cancel(); + usageCount--; + if (usageCount == 0) { executor.shutdown(); try { executor.awaitTermination(timeout, unit); @@ -126,95 +107,23 @@ class EvictionTimer { } /** - * Removes evictor from the task set and executor. - * Only called when holding the class lock. - * - * @param evictor Eviction task to remove - */ - private static void remove(final BaseGenericObjectPool.Evictor evictor) { - for (Entry, WeakRunner> entry : taskMap.entrySet()) { - if (entry.getKey().get() == evictor) { - executor.remove(entry.getValue()); - taskMap.remove(entry.getKey()); - break; - } - } - } - - /** - * @return the number of eviction tasks under management. - */ - static synchronized int getNumTasks() { - return taskMap.size(); - } - - /** - * Thread factory that creates a daemon thread, with the context class loader from this class. + * Thread factory that creates a thread, with the context classloader from this class. */ private static class EvictorThreadFactory implements ThreadFactory { @Override - public Thread newThread(final Runnable runnable) { - final Thread thread = new Thread(null, runnable, "commons-pool-evictor-thread"); - thread.setDaemon(true); // POOL-363 - Required for applications using Runtime.addShutdownHook(). - AccessController.doPrivileged((PrivilegedAction) () -> { - thread.setContextClassLoader(EvictorThreadFactory.class.getClassLoader()); - return null; - }); - - return thread; - } - } - - /** - * Task that removes references to abandoned tasks and shuts - * down the executor if there are no live tasks left. - */ - private static class Reaper implements Runnable { - @Override - public void run() { - synchronized (EvictionTimer.class) { - for (Entry, WeakRunner> entry : taskMap.entrySet()) { - if (entry.getKey().get() == null) { - executor.remove(entry.getValue()); - taskMap.remove(entry.getKey()); - } + public Thread newThread(final Runnable r) { + final Thread t = new Thread(null, r, "commons-pool-evictor-thread"); + + AccessController.doPrivileged(new PrivilegedAction() { + @Override + public Void run() { + t.setContextClassLoader(EvictorThreadFactory.class.getClassLoader()); + return null; } - if (taskMap.isEmpty() && executor != null) { - executor.shutdown(); - executor.setCorePoolSize(0); - executor = null; - } - } - } - } - - /** - * Runnable that runs the referent of a weak reference. When the referent is no - * no longer reachable, run is no-op. - */ - private static class WeakRunner implements Runnable { - - private final WeakReference ref; - - /** - * Constructs a new instance to track the given reference. - * - * @param ref the reference to track. - */ - private WeakRunner(final WeakReference ref) { - this.ref = ref; - } + }); - @Override - public void run() { - final Runnable task = ref.get(); - if (task != null) { - task.run(); - } else { - executor.remove(this); - taskMap.remove(ref); - } + return t; } } } diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericKeyedObjectPool.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericKeyedObjectPool.java index 7d33be1e3..06f0f3a00 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericKeyedObjectPool.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericKeyedObjectPool.java @@ -33,7 +33,6 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; -import com.fr.third.org.apache.commons.pool2.DestroyMode; import com.fr.third.org.apache.commons.pool2.KeyedObjectPool; import com.fr.third.org.apache.commons.pool2.KeyedPooledObjectFactory; import com.fr.third.org.apache.commons.pool2.PoolUtils; @@ -42,22 +41,20 @@ import com.fr.third.org.apache.commons.pool2.PooledObjectState; import com.fr.third.org.apache.commons.pool2.SwallowedExceptionListener; /** - * A configurable {@code KeyedObjectPool} implementation. + * A configurable KeyedObjectPool implementation. *

    * When coupled with the appropriate {@link KeyedPooledObjectFactory}, - * {@code GenericKeyedObjectPool} provides robust pooling functionality for - * keyed objects. A {@code GenericKeyedObjectPool} can be viewed as a map + * GenericKeyedObjectPool provides robust pooling functionality for + * keyed objects. A GenericKeyedObjectPool can be viewed as a map * of sub-pools, keyed on the (unique) key values provided to the * {@link #preparePool preparePool}, {@link #addObject addObject} or * {@link #borrowObject borrowObject} methods. Each time a new key value is * provided to one of these methods, a sub-new pool is created under the given - * key to be managed by the containing {@code GenericKeyedObjectPool.} - *

    + * key to be managed by the containing GenericKeyedObjectPool. *

    * Note that the current implementation uses a ConcurrentHashMap which uses * equals() to compare keys. * This means that distinct instance keys must be distinguishable using equals. - *

    *

    * Optionally, one may configure the pool to examine and possibly evict objects * as they sit idle in the pool and to ensure that a minimum number of idle @@ -66,15 +63,12 @@ import com.fr.third.org.apache.commons.pool2.SwallowedExceptionListener; * configuring this optional feature. Eviction runs contend with client threads * for access to objects in the pool, so if they run too frequently performance * issues may result. - *

    *

    * Implementation note: To prevent possible deadlocks, care has been taken to * ensure that no call to a factory method will occur within a synchronization * block. See POOL-125 and DBCP-44 for more information. - *

    *

    * This class is intended to be thread-safe. - *

    * * @see GenericObjectPool * @@ -83,20 +77,20 @@ import com.fr.third.org.apache.commons.pool2.SwallowedExceptionListener; * * @since 2.0 */ -public class GenericKeyedObjectPool extends BaseGenericObjectPool - implements KeyedObjectPool, GenericKeyedObjectPoolMXBean { +public class GenericKeyedObjectPool extends BaseGenericObjectPool + implements KeyedObjectPool, GenericKeyedObjectPoolMXBean { /** - * Create a new {@code GenericKeyedObjectPool} using defaults from + * Create a new GenericKeyedObjectPool using defaults from * {@link GenericKeyedObjectPoolConfig}. * @param factory the factory to be used to create entries */ - public GenericKeyedObjectPool(final KeyedPooledObjectFactory factory) { - this(factory, new GenericKeyedObjectPoolConfig()); + public GenericKeyedObjectPool(final KeyedPooledObjectFactory factory) { + this(factory, new GenericKeyedObjectPoolConfig()); } /** - * Create a new {@code GenericKeyedObjectPool} using a specific + * Create a new GenericKeyedObjectPool using a specific * configuration. * * @param factory the factory to be used to create entries @@ -105,8 +99,8 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool * the configuration object will not be reflected in the * pool. */ - public GenericKeyedObjectPool(final KeyedPooledObjectFactory factory, - final GenericKeyedObjectPoolConfig config) { + public GenericKeyedObjectPool(final KeyedPooledObjectFactory factory, + final GenericKeyedObjectPoolConfig config) { super(config, ONAME_BASE, config.getJmxNamePrefix()); @@ -118,6 +112,8 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool this.fairness = config.getFairness(); setConfig(config); + + startEvictor(getTimeBetweenEvictionRunsMillis()); } /** @@ -242,12 +238,26 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool * * @see GenericKeyedObjectPoolConfig */ - public void setConfig(final GenericKeyedObjectPoolConfig conf) { - super.setConfig(conf); + public void setConfig(final GenericKeyedObjectPoolConfig conf) { + setLifo(conf.getLifo()); setMaxIdlePerKey(conf.getMaxIdlePerKey()); setMaxTotalPerKey(conf.getMaxTotalPerKey()); setMaxTotal(conf.getMaxTotal()); setMinIdlePerKey(conf.getMinIdlePerKey()); + setMaxWaitMillis(conf.getMaxWaitMillis()); + setBlockWhenExhausted(conf.getBlockWhenExhausted()); + setTestOnCreate(conf.getTestOnCreate()); + setTestOnBorrow(conf.getTestOnBorrow()); + setTestOnReturn(conf.getTestOnReturn()); + setTestWhileIdle(conf.getTestWhileIdle()); + setNumTestsPerEvictionRun(conf.getNumTestsPerEvictionRun()); + setMinEvictableIdleTimeMillis(conf.getMinEvictableIdleTimeMillis()); + setSoftMinEvictableIdleTimeMillis( + conf.getSoftMinEvictableIdleTimeMillis()); + setTimeBetweenEvictionRunsMillis( + conf.getTimeBetweenEvictionRunsMillis()); + setEvictionPolicyClassName(conf.getEvictionPolicyClassName()); + setEvictorShutdownTimeoutMillis(conf.getEvictorShutdownTimeoutMillis()); } /** @@ -280,7 +290,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool * associated with the given key, then an idle instance will be selected * based on the value of {@link #getLifo()}, activated and returned. If * activation fails, or {@link #getTestOnBorrow() testOnBorrow} is set to - * {@code true} and validation fails, the instance is destroyed and the + * true and validation fails, the instance is destroyed and the * next available instance is examined. This continues until either a valid * instance is returned or there are no more idle instances available. *

    @@ -288,24 +298,24 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool * the given key, behavior depends on the {@link #getMaxTotalPerKey() * maxTotalPerKey}, {@link #getMaxTotal() maxTotal}, and (if applicable) * {@link #getBlockWhenExhausted()} and the value passed in to the - * {@code borrowMaxWaitMillis} parameter. If the number of instances checked + * borrowMaxWaitMillis parameter. If the number of instances checked * out from the sub-pool under the given key is less than - * {@code maxTotalPerKey} and the total number of instances in - * circulation (under all keys) is less than {@code maxTotal}, a new + * maxTotalPerKey and the total number of instances in + * circulation (under all keys) is less than maxTotal, a new * instance is created, activated and (if applicable) validated and returned - * to the caller. If validation fails, a {@code NoSuchElementException} + * to the caller. If validation fails, a NoSuchElementException * will be thrown. *

    * If the associated sub-pool is exhausted (no available idle instances and * no capacity to create new ones), this method will either block * ({@link #getBlockWhenExhausted()} is true) or throw a - * {@code NoSuchElementException} + * NoSuchElementException * ({@link #getBlockWhenExhausted()} is false). * The length of time that this method will block when * {@link #getBlockWhenExhausted()} is true is determined by the value - * passed in to the {@code borrowMaxWait} parameter. + * passed in to the borrowMaxWait parameter. *

    - * When {@code maxTotal} is set to a positive value and this method is + * When maxTotal is set to a positive value and this method is * invoked when at the limit with no idle instances available under the requested * key, an attempt is made to create room by clearing the oldest 15% of the * elements from the keyed sub-pools. @@ -377,7 +387,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool factory.activateObject(key, p); } catch (final Exception e) { try { - destroy(key, p, true, DestroyMode.NORMAL); + destroy(key, p, true); } catch (final Exception e1) { // Ignore - activation failure is more important } @@ -389,7 +399,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool throw nsee; } } - if (p != null && getTestOnBorrow()) { + if (p != null && (getTestOnBorrow() || create && getTestOnCreate())) { boolean validate = false; Throwable validationThrowable = null; try { @@ -400,7 +410,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool } if (!validate) { try { - destroy(key, p, true, DestroyMode.NORMAL); + destroy(key, p, true); destroyedByBorrowValidationCount.incrementAndGet(); } catch (final Exception e) { // Ignore - validation failure is more important @@ -453,31 +463,41 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool final ObjectDeque objectDeque = poolMap.get(key); - if (objectDeque == null) { - throw new IllegalStateException( - "No keyed pool found under the given key."); - } - - final PooledObject p = objectDeque.getAllObjects().get(new IdentityWrapper<>(obj)); + final PooledObject p = objectDeque.getAllObjects().get(new IdentityWrapper(obj)); if (p == null) { throw new IllegalStateException( "Returned object not currently part of this pool"); } - markReturningState(p); + synchronized(p) { + final PooledObjectState state = p.getState(); + if (state != PooledObjectState.ALLOCATED) { + throw new IllegalStateException( + "Object has already been returned to this pool or is invalid"); + } + p.markReturning(); // Keep from being marked abandoned (once GKOP does this) + } final long activeTime = p.getActiveTimeMillis(); try { - if (getTestOnReturn() && !factory.validateObject(key, p)) { - try { - destroy(key, p, true, DestroyMode.NORMAL); - } catch (final Exception e) { - swallowException(e); + if (getTestOnReturn()) { + if (!factory.validateObject(key, p)) { + try { + destroy(key, p, true); + } catch (final Exception e) { + swallowException(e); + } + if (objectDeque.idleObjects.hasTakeWaiters()) { + try { + addObject(key); + } catch (final Exception e) { + swallowException(e); + } + } + return; } - whenWaitersAddObject(key, objectDeque.idleObjects); - return; } try { @@ -485,11 +505,17 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool } catch (final Exception e1) { swallowException(e1); try { - destroy(key, p, true, DestroyMode.NORMAL); + destroy(key, p, true); } catch (final Exception e) { swallowException(e); } - whenWaitersAddObject(key, objectDeque.idleObjects); + if (objectDeque.idleObjects.hasTakeWaiters()) { + try { + addObject(key); + } catch (final Exception e) { + swallowException(e); + } + } return; } @@ -504,7 +530,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool if (isClosed() || maxIdle > -1 && maxIdle <= idleObjects.size()) { try { - destroy(key, p, true, DestroyMode.NORMAL); + destroy(key, p, true); } catch (final Exception e) { swallowException(e); } @@ -529,26 +555,12 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool } } - /** - * Whether there is at least one thread waiting on this deque, add an pool object. - * @param key pool key. - * @param idleObjects list of idle pool objects. - */ - private void whenWaitersAddObject(final K key, final LinkedBlockingDeque> idleObjects) { - if (idleObjects.hasTakeWaiters()) { - try { - addObject(key); - } catch (final Exception e) { - swallowException(e); - } - } - } /** * {@inheritDoc} *

    * Activation of this method decrements the active count associated with - * the given keyed pool and attempts to destroy {@code obj.} + * the given keyed pool and attempts to destroy obj. * * @param key pool key * @param obj instance to invalidate @@ -560,38 +572,17 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool */ @Override public void invalidateObject(final K key, final T obj) throws Exception { - invalidateObject(key, obj, DestroyMode.NORMAL); - } - - /** - * {@inheritDoc} - *

    - * Activation of this method decrements the active count associated with - * the given keyed pool and attempts to destroy {@code obj.} - * - * @param key pool key - * @param obj instance to invalidate - * @param mode DestroyMode context provided to factory - * - * @throws Exception if an exception occurs destroying the - * object - * @throws IllegalStateException if obj does not belong to the pool - * under the given key - * @since 2.9.0 - */ - @Override - public void invalidateObject(final K key, final T obj, final DestroyMode mode) throws Exception { final ObjectDeque objectDeque = poolMap.get(key); - final PooledObject p = objectDeque.getAllObjects().get(new IdentityWrapper<>(obj)); + final PooledObject p = objectDeque.getAllObjects().get(new IdentityWrapper(obj)); if (p == null) { throw new IllegalStateException( "Object not currently part of this pool"); } synchronized (p) { if (p.getState() != PooledObjectState.INVALID) { - destroy(key, p, true, mode); + destroy(key, p, true); } } if (objectDeque.idleObjects.hasTakeWaiters()) { @@ -630,7 +621,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool /** * Clears the specified sub-pool, removing all pooled instances - * corresponding to the given {@code key}. Exceptions encountered + * corresponding to the given key. Exceptions encountered * destroying idle instances are swallowed but notified via a * {@link SwallowedExceptionListener}. * @@ -649,7 +640,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool while (p != null) { try { - destroy(key, p, true, DestroyMode.NORMAL); + destroy(key, p, true); } catch (final Exception e) { swallowException(e); } @@ -720,7 +711,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool // Stop the evictor before the pool is closed since evict() calls // assertOpen() - stopEvictor(); + startEvictor(-1L); closed = true; // This clear removes any idle objects @@ -747,9 +738,9 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool public void clearOldest() { // build sorted map of idle objects - final Map, K> map = new TreeMap<>(); + final Map, K> map = new TreeMap, K>(); - for (final Map.Entry> entry : poolMap.entrySet()) { + for (final Entry> entry : poolMap.entrySet()) { final K k = entry.getKey(); final ObjectDeque deque = entry.getValue(); // Protect against possible NPE if key has been removed in another @@ -768,11 +759,11 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool // Now iterate created map and kill the first 15% plus one to account // for zero int itemsToRemove = ((int) (map.size() * 0.15)) + 1; - final Iterator, K>> iter = + final Iterator, K>> iter = map.entrySet().iterator(); while (iter.hasNext() && itemsToRemove > 0) { - final Map.Entry, K> entry = iter.next(); + final Entry, K> entry = iter.next(); // kind of backwards on naming. In the map, each key is the // PooledObject because it has the ordering with the timestamp // value. Each value that the key references is the key of the @@ -782,7 +773,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool // Assume the destruction succeeds boolean destroyed = true; try { - destroyed = destroy(key, p, false, DestroyMode.NORMAL); + destroyed = destroy(key, p, false); } catch (final Exception e) { swallowException(e); } @@ -812,7 +803,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool int maxQueueLength = 0; LinkedBlockingDeque> mostLoaded = null; K loadedKey = null; - for (final Map.Entry> entry : poolMap.entrySet()) { + for (final Entry> entry : poolMap.entrySet()) { final K k = entry.getKey(); final ObjectDeque deque = entry.getValue(); if (deque != null) { @@ -850,7 +841,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool * {@code false} */ private boolean hasBorrowWaiters() { - for (final Map.Entry> entry : poolMap.entrySet()) { + for (final Entry> entry : poolMap.entrySet()) { final ObjectDeque deque = entry.getValue(); if (deque != null) { final LinkedBlockingDeque> pool = @@ -894,7 +885,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool if(evictionIterator == null || !evictionIterator.hasNext()) { if (evictionKeyIterator == null || !evictionKeyIterator.hasNext()) { - final List keyCopy = new ArrayList<>(); + final List keyCopy = new ArrayList(); final Lock readLock = keyLock.readLock(); readLock.lock(); try { @@ -959,7 +950,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool } if (evict) { - destroy(evictionKey, underTest, true, DestroyMode.NORMAL); + destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { if (testWhileIdle) { @@ -968,18 +959,18 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool factory.activateObject(evictionKey, underTest); active = true; } catch (final Exception e) { - destroy(evictionKey, underTest, true, DestroyMode.NORMAL); + destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } if (active) { if (!factory.validateObject(evictionKey, underTest)) { - destroy(evictionKey, underTest, true, DestroyMode.NORMAL); + destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { try { factory.passivateObject(evictionKey, underTest); } catch (final Exception e) { - destroy(evictionKey, underTest, true, DestroyMode.NORMAL); + destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } } @@ -1071,11 +1062,6 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool PooledObject p = null; try { p = factory.makeObject(key); - if (getTestOnCreate() && !factory.validateObject(key, p)) { - numTotal.decrementAndGet(); - objectDeque.getCreateCount().decrementAndGet(); - return null; - } } catch (final Exception e) { numTotal.decrementAndGet(); objectDeque.getCreateCount().decrementAndGet(); @@ -1088,7 +1074,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool } createdCount.incrementAndGet(); - objectDeque.getAllObjects().put(new IdentityWrapper<>(p.getObject()), p); + objectDeque.getAllObjects().put(new IdentityWrapper(p.getObject()), p); return p; } @@ -1099,33 +1085,23 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool * @param toDestroy The wrapped object to be destroyed * @param always Should the object be destroyed even if it is not currently * in the set of idle objects for the given key - * @param mode DestroyMode context provided to the factory - * * @return {@code true} if the object was destroyed, otherwise {@code false} * @throws Exception If the object destruction failed */ - private boolean destroy(final K key, final PooledObject toDestroy, final boolean always, final DestroyMode mode) + private boolean destroy(final K key, final PooledObject toDestroy, final boolean always) throws Exception { final ObjectDeque objectDeque = register(key); try { - boolean isIdle; - synchronized(toDestroy) { - // Check idle state directly - isIdle = toDestroy.getState().equals(PooledObjectState.IDLE); - // If idle, not under eviction test, or always is true, remove instance, - // updating isIdle if instance is found in idle objects - if (isIdle || always) { - isIdle = objectDeque.getIdleObjects().remove(toDestroy); - } - } + final boolean isIdle = objectDeque.getIdleObjects().remove(toDestroy); + if (isIdle || always) { - objectDeque.getAllObjects().remove(new IdentityWrapper<>(toDestroy.getObject())); + objectDeque.getAllObjects().remove(new IdentityWrapper(toDestroy.getObject())); toDestroy.invalidate(); try { - factory.destroyObject(key, toDestroy, mode); + factory.destroyObject(key, toDestroy); } finally { objectDeque.getCreateCount().decrementAndGet(); destroyedCount.incrementAndGet(); @@ -1164,7 +1140,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool lock.lock(); objectDeque = poolMap.get(k); if (objectDeque == null) { - objectDeque = new ObjectDeque<>(fairness); + objectDeque = new ObjectDeque(fairness); objectDeque.getNumInterested().incrementAndGet(); // NOTE: Keys must always be added to both poolMap and // poolKeyList at the same time while protected by @@ -1191,27 +1167,26 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool * @param k The key to de-register */ private void deregister(final K k) { - Lock lock = keyLock.readLock(); - try { - lock.lock(); - final ObjectDeque objectDeque = poolMap.get(k); - final long numInterested = objectDeque.getNumInterested().decrementAndGet(); - if (numInterested == 0 && objectDeque.getCreateCount().get() == 0) { - // Potential to remove key - // Upgrade to write lock - lock.unlock(); - lock = keyLock.writeLock(); - lock.lock(); - if (objectDeque.getCreateCount().get() == 0 && objectDeque.getNumInterested().get() == 0) { + ObjectDeque objectDeque; + + objectDeque = poolMap.get(k); + final long numInterested = objectDeque.getNumInterested().decrementAndGet(); + if (numInterested == 0 && objectDeque.getCreateCount().get() == 0) { + // Potential to remove key + final Lock writeLock = keyLock.writeLock(); + writeLock.lock(); + try { + if (objectDeque.getCreateCount().get() == 0 && + objectDeque.getNumInterested().get() == 0) { // NOTE: Keys must always be removed from both poolMap and // poolKeyList at the same time while protected by // keyLock.writeLock() poolMap.remove(k); poolKeyList.remove(k); } + } finally { + writeLock.unlock(); } - } finally { - lock.unlock(); } } @@ -1263,7 +1238,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool /** * Create an object using the {@link KeyedPooledObjectFactory#makeObject * factory}, passivate it, and then place it in the idle object pool. - * {@code addObject} is useful for "pre-loading" a pool with idle + * addObject is useful for "pre-loading" a pool with idle * objects. * * @param key the key a new instance should be added to @@ -1380,7 +1355,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool @Override public Map getNumActivePerKey() { - final HashMap result = new HashMap<>(); + final HashMap result = new HashMap(); final Iterator>> iter = poolMap.entrySet().iterator(); while (iter.hasNext()) { @@ -1432,9 +1407,9 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool */ @Override public Map getNumWaitersByKey() { - final Map result = new HashMap<>(); + final Map result = new HashMap(); - for (final Map.Entry> entry : poolMap.entrySet()) { + for (final Entry> entry : poolMap.entrySet()) { final K k = entry.getKey(); final ObjectDeque deque = entry.getValue(); if (deque != null) { @@ -1463,14 +1438,14 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool @Override public Map> listAllObjects() { final Map> result = - new HashMap<>(); + new HashMap>(); - for (final Map.Entry> entry : poolMap.entrySet()) { + for (final Entry> entry : poolMap.entrySet()) { final K k = entry.getKey(); final ObjectDeque deque = entry.getValue(); if (deque != null) { final List list = - new ArrayList<>(); + new ArrayList(); result.put(k.toString(), list); for (final PooledObject p : deque.getAllObjects().values()) { list.add(new DefaultPooledObjectInfo(p)); @@ -1506,7 +1481,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool * they work properly as keys. */ private final Map, PooledObject> allObjects = - new ConcurrentHashMap<>(); + new ConcurrentHashMap, PooledObject>(); /* * Number of threads with registered interest in this key. @@ -1522,7 +1497,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool * will be served as if waiting in a FIFO queue. */ public ObjectDeque(final boolean fairness) { - idleObjects = new LinkedBlockingDeque<>(fairness); + idleObjects = new LinkedBlockingDeque>(fairness); } /** @@ -1586,7 +1561,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool GenericKeyedObjectPoolConfig.DEFAULT_MIN_IDLE_PER_KEY; private volatile int maxTotalPerKey = GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL_PER_KEY; - private final KeyedPooledObjectFactory factory; + private final KeyedPooledObjectFactory factory; private final boolean fairness; @@ -1597,15 +1572,15 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool * in step with {@link #poolKeyList} using {@link #keyLock} to ensure any * changes to the list of current keys is made in a thread-safe manner. */ - private final Map> poolMap = - new ConcurrentHashMap<>(); // @GuardedBy("keyLock") for write access (and some read access) + private final Map> poolMap = + new ConcurrentHashMap>(); // @GuardedBy("keyLock") for write access (and some read access) /* * List of pool keys - used to control eviction order. The list of keys * must be kept in step with {@link #poolMap} using {@link #keyLock} * to ensure any changes to the list of current keys is made in a * thread-safe manner. */ - private final List poolKeyList = new ArrayList<>(); // @GuardedBy("keyLock") + private final List poolKeyList = new ArrayList(); // @GuardedBy("keyLock") private final ReadWriteLock keyLock = new ReentrantReadWriteLock(true); /* * The combined count of the currently active objects for all keys and those @@ -1619,7 +1594,7 @@ public class GenericKeyedObjectPool extends BaseGenericObjectPool // JMX specific attributes private static final String ONAME_BASE = - "org.apache.commons.pool2:type=GenericKeyedObjectPool,name="; + "com.fr.third.org.apache.commons.pool2:type=GenericKeyedObjectPool,name="; @Override protected void toStringAppendFields(final StringBuilder builder) { diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericKeyedObjectPoolConfig.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericKeyedObjectPoolConfig.java index 3c18e95d3..474cd449a 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericKeyedObjectPoolConfig.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericKeyedObjectPoolConfig.java @@ -23,12 +23,10 @@ package com.fr.third.org.apache.commons.pool2.impl; *

    * This class is not thread-safe; it is only intended to be used to provide * attributes used when creating a pool. - *

    * - * @param Type of element pooled. * @since 2.0 */ -public class GenericKeyedObjectPoolConfig extends BaseObjectPoolConfig { +public class GenericKeyedObjectPoolConfig extends BaseObjectPoolConfig { /** * The default value for the {@code maxTotalPerKey} configuration attribute. @@ -173,11 +171,10 @@ public class GenericKeyedObjectPoolConfig extends BaseObjectPoolConfig { this.maxIdlePerKey = maxIdlePerKey; } - @SuppressWarnings("unchecked") @Override - public GenericKeyedObjectPoolConfig clone() { + public GenericKeyedObjectPoolConfig clone() { try { - return (GenericKeyedObjectPoolConfig) super.clone(); + return (GenericKeyedObjectPoolConfig) super.clone(); } catch (final CloneNotSupportedException e) { throw new AssertionError(); // Can't happen } diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericKeyedObjectPoolMXBean.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericKeyedObjectPoolMXBean.java index e99ba214b..808089ce3 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericKeyedObjectPoolMXBean.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericKeyedObjectPoolMXBean.java @@ -34,204 +34,169 @@ import java.util.Map; * @since 2.0 */ public interface GenericKeyedObjectPoolMXBean { - // Expose getters for configuration settings - /** * See {@link GenericKeyedObjectPool#getBlockWhenExhausted()} * @return See {@link GenericKeyedObjectPool#getBlockWhenExhausted()} */ boolean getBlockWhenExhausted(); - /** * See {@link GenericKeyedObjectPool#getFairness()} * @return See {@link GenericKeyedObjectPool#getFairness()} */ boolean getFairness(); - /** * See {@link GenericKeyedObjectPool#getLifo()} * @return See {@link GenericKeyedObjectPool#getLifo()} */ boolean getLifo(); - /** * See {@link GenericKeyedObjectPool#getMaxIdlePerKey()} * @return See {@link GenericKeyedObjectPool#getMaxIdlePerKey()} */ int getMaxIdlePerKey(); - /** * See {@link GenericKeyedObjectPool#getMaxTotal()} * @return See {@link GenericKeyedObjectPool#getMaxTotal()} */ int getMaxTotal(); - /** * See {@link GenericKeyedObjectPool#getMaxTotalPerKey()} * @return See {@link GenericKeyedObjectPool#getMaxTotalPerKey()} */ int getMaxTotalPerKey(); - /** * See {@link GenericKeyedObjectPool#getMaxWaitMillis()} * @return See {@link GenericKeyedObjectPool#getMaxWaitMillis()} */ long getMaxWaitMillis(); - /** * See {@link GenericKeyedObjectPool#getMinEvictableIdleTimeMillis()} * @return See {@link GenericKeyedObjectPool#getMinEvictableIdleTimeMillis()} */ long getMinEvictableIdleTimeMillis(); - /** * See {@link GenericKeyedObjectPool#getMinIdlePerKey()} * @return See {@link GenericKeyedObjectPool#getMinIdlePerKey()} */ int getMinIdlePerKey(); - /** * See {@link GenericKeyedObjectPool#getNumActive()} * @return See {@link GenericKeyedObjectPool#getNumActive()} */ int getNumActive(); - /** * See {@link GenericKeyedObjectPool#getNumIdle()} * @return See {@link GenericKeyedObjectPool#getNumIdle()} */ int getNumIdle(); - /** * See {@link GenericKeyedObjectPool#getNumTestsPerEvictionRun()} * @return See {@link GenericKeyedObjectPool#getNumTestsPerEvictionRun()} */ int getNumTestsPerEvictionRun(); - /** * See {@link GenericKeyedObjectPool#getTestOnCreate()} * @return See {@link GenericKeyedObjectPool#getTestOnCreate()} * @since 2.2 */ boolean getTestOnCreate(); - /** * See {@link GenericKeyedObjectPool#getTestOnBorrow()} * @return See {@link GenericKeyedObjectPool#getTestOnBorrow()} */ boolean getTestOnBorrow(); - /** * See {@link GenericKeyedObjectPool#getTestOnReturn()} * @return See {@link GenericKeyedObjectPool#getTestOnReturn()} */ boolean getTestOnReturn(); - /** * See {@link GenericKeyedObjectPool#getTestWhileIdle()} * @return See {@link GenericKeyedObjectPool#getTestWhileIdle()} */ boolean getTestWhileIdle(); - /** * See {@link GenericKeyedObjectPool#getTimeBetweenEvictionRunsMillis()} * @return See {@link GenericKeyedObjectPool#getTimeBetweenEvictionRunsMillis()} */ long getTimeBetweenEvictionRunsMillis(); - /** * See {@link GenericKeyedObjectPool#isClosed()} * @return See {@link GenericKeyedObjectPool#isClosed()} */ boolean isClosed(); - // Expose getters for monitoring attributes - /** * See {@link GenericKeyedObjectPool#getNumActivePerKey()} * @return See {@link GenericKeyedObjectPool#getNumActivePerKey()} */ Map getNumActivePerKey(); - /** * See {@link GenericKeyedObjectPool#getBorrowedCount()} * @return See {@link GenericKeyedObjectPool#getBorrowedCount()} */ long getBorrowedCount(); - /** * See {@link GenericKeyedObjectPool#getReturnedCount()} * @return See {@link GenericKeyedObjectPool#getReturnedCount()} */ long getReturnedCount(); - /** * See {@link GenericKeyedObjectPool#getCreatedCount()} * @return See {@link GenericKeyedObjectPool#getCreatedCount()} */ long getCreatedCount(); - /** * See {@link GenericKeyedObjectPool#getDestroyedCount()} * @return See {@link GenericKeyedObjectPool#getDestroyedCount()} */ long getDestroyedCount(); - /** * See {@link GenericKeyedObjectPool#getDestroyedByEvictorCount()} * @return See {@link GenericKeyedObjectPool#getDestroyedByEvictorCount()} */ long getDestroyedByEvictorCount(); - /** * See {@link GenericKeyedObjectPool#getDestroyedByBorrowValidationCount()} * @return See {@link GenericKeyedObjectPool#getDestroyedByBorrowValidationCount()} */ long getDestroyedByBorrowValidationCount(); - /** * See {@link GenericKeyedObjectPool#getMeanActiveTimeMillis()} * @return See {@link GenericKeyedObjectPool#getMeanActiveTimeMillis()} */ long getMeanActiveTimeMillis(); - /** * See {@link GenericKeyedObjectPool#getMeanIdleTimeMillis()} * @return See {@link GenericKeyedObjectPool#getMeanIdleTimeMillis()} */ long getMeanIdleTimeMillis(); - /** * See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()} * @return See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()} */ long getMeanBorrowWaitTimeMillis(); - /** * See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()} * @return See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()} */ long getMaxBorrowWaitTimeMillis(); - /** * See {@link GenericKeyedObjectPool#getCreationStackTrace()} * @return See {@link GenericKeyedObjectPool#getCreationStackTrace()} */ String getCreationStackTrace(); - /** * See {@link GenericKeyedObjectPool#getNumWaiters()} * @return See {@link GenericKeyedObjectPool#getNumWaiters()} */ int getNumWaiters(); - /** * See {@link GenericKeyedObjectPool#getNumWaitersByKey()} * @return See {@link GenericKeyedObjectPool#getNumWaitersByKey()} */ Map getNumWaitersByKey(); - /** * See {@link GenericKeyedObjectPool#listAllObjects()} * @return See {@link GenericKeyedObjectPool#listAllObjects()} diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericObjectPool.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericObjectPool.java index 1a1ed1fc7..de9ba23fe 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericObjectPool.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericObjectPool.java @@ -16,7 +16,6 @@ */ package com.fr.third.org.apache.commons.pool2.impl; -import com.fr.third.org.apache.commons.pool2.DestroyMode; import com.fr.third.org.apache.commons.pool2.ObjectPool; import com.fr.third.org.apache.commons.pool2.PoolUtils; import com.fr.third.org.apache.commons.pool2.PooledObject; @@ -40,9 +39,8 @@ import java.util.concurrent.atomic.AtomicLong; * A configurable {@link ObjectPool} implementation. *

    * When coupled with the appropriate {@link PooledObjectFactory}, - * {@code GenericObjectPool} provides robust pooling functionality for - * arbitrary objects. - *

    + * GenericObjectPool provides robust pooling functionality for + * arbitrary objects.

    *

    * Optionally, one may configure the pool to examine and possibly evict objects * as they sit idle in the pool and to ensure that a minimum number of idle @@ -50,29 +48,25 @@ import java.util.concurrent.atomic.AtomicLong; * which runs asynchronously. Caution should be used when configuring this * optional feature. Eviction runs contend with client threads for access to * objects in the pool, so if they run too frequently performance issues may - * result. - *

    + * result.

    *

    * The pool can also be configured to detect and remove "abandoned" objects, * i.e. objects that have been checked out of the pool but neither used nor * returned before the configured * {@link AbandonedConfig#getRemoveAbandonedTimeout() removeAbandonedTimeout}. * Abandoned object removal can be configured to happen when - * {@code borrowObject} is invoked and the pool is close to starvation, or + * borrowObject is invoked and the pool is close to starvation, or * it can be executed by the idle object evictor, or both. If pooled objects * implement the {@link TrackedUse} interface, their last use will be queried - * using the {@code getLastUsed} method on that interface; otherwise + * using the getLastUsed method on that interface; otherwise * abandonment is determined by how long an object has been checked out from - * the pool. - *

    + * the pool.

    *

    * Implementation note: To prevent possible deadlocks, care has been taken to * ensure that no call to a factory method will occur within a synchronization - * block. See POOL-125 and DBCP-44 for more information. - *

    + * block. See POOL-125 and DBCP-44 for more information.

    *

    - * This class is intended to be thread-safe. - *

    + * This class is intended to be thread-safe.

    * * @see GenericKeyedObjectPool * @@ -84,18 +78,18 @@ public class GenericObjectPool extends BaseGenericObjectPool implements ObjectPool, GenericObjectPoolMXBean, UsageTracking { /** - * Creates a new {@code GenericObjectPool} using defaults from + * Create a new GenericObjectPool using defaults from * {@link GenericObjectPoolConfig}. * * @param factory The object factory to be used to create object instances * used by this pool */ public GenericObjectPool(final PooledObjectFactory factory) { - this(factory, new GenericObjectPoolConfig()); + this(factory, new GenericObjectPoolConfig()); } /** - * Creates a new {@code GenericObjectPool} using a specific + * Create a new GenericObjectPool using a specific * configuration. * * @param factory The object factory to be used to create object instances @@ -106,7 +100,7 @@ public class GenericObjectPool extends BaseGenericObjectPool * pool. */ public GenericObjectPool(final PooledObjectFactory factory, - final GenericObjectPoolConfig config) { + final GenericObjectPoolConfig config) { super(config, ONAME_BASE, config.getJmxNamePrefix()); @@ -116,13 +110,15 @@ public class GenericObjectPool extends BaseGenericObjectPool } this.factory = factory; - idleObjects = new LinkedBlockingDeque<>(config.getFairness()); + idleObjects = new LinkedBlockingDeque>(config.getFairness()); setConfig(config); + + startEvictor(getTimeBetweenEvictionRunsMillis()); } /** - * Creates a new {@code GenericObjectPool} that tracks and destroys + * Create a new GenericObjectPool that tracks and destroys * objects that are checked out, but never returned to the pool. * * @param factory The object factory to be used to create object instances @@ -135,7 +131,7 @@ public class GenericObjectPool extends BaseGenericObjectPool * and removal. The configuration is used by value. */ public GenericObjectPool(final PooledObjectFactory factory, - final GenericObjectPoolConfig config, final AbandonedConfig abandonedConfig) { + final GenericObjectPoolConfig config, final AbandonedConfig abandonedConfig) { this(factory, config); setAbandonedConfig(abandonedConfig); } @@ -188,7 +184,6 @@ public class GenericObjectPool extends BaseGenericObjectPool *

    * If the configured value of minIdle is greater than the configured value * for maxIdle then the value of maxIdle will be used instead. - *

    * * @param minIdle * The minimum number of objects. @@ -210,7 +205,6 @@ public class GenericObjectPool extends BaseGenericObjectPool *

    * If the configured value of minIdle is greater than the configured value * for maxIdle then the value of maxIdle will be used instead. - *

    * * @return The minimum number of objects. * @@ -228,7 +222,7 @@ public class GenericObjectPool extends BaseGenericObjectPool } /** - * Gets whether or not abandoned object removal is configured for this pool. + * Whether or not abandoned object removal is configured for this pool. * * @return true if this pool is configured to detect and remove * abandoned objects @@ -239,7 +233,7 @@ public class GenericObjectPool extends BaseGenericObjectPool } /** - * Gets whether this pool identifies and logs any abandoned objects. + * Will this pool identify and log any abandoned objects? * * @return {@code true} if abandoned object removal is configured for this * pool and removal events are to be logged otherwise {@code false} @@ -253,8 +247,8 @@ public class GenericObjectPool extends BaseGenericObjectPool } /** - * Gets whether a check is made for abandoned objects when an object is borrowed - * from this pool. + * Will a check be made for abandoned objects when an object is borrowed + * from this pool? * * @return {@code true} if abandoned object removal is configured to be * activated by borrowObject otherwise {@code false} @@ -268,7 +262,7 @@ public class GenericObjectPool extends BaseGenericObjectPool } /** - * Gets whether a check is made for abandoned objects when the evictor runs. + * Will a check be made for abandoned objects when the evictor runs? * * @return {@code true} if abandoned object removal is configured to be * activated when the evictor runs otherwise {@code false} @@ -282,7 +276,7 @@ public class GenericObjectPool extends BaseGenericObjectPool } /** - * Obtains the timeout before which an object will be considered to be + * Obtain the timeout before which an object will be considered to be * abandoned by this pool. * * @return The abandoned object timeout in seconds if abandoned object @@ -304,11 +298,25 @@ public class GenericObjectPool extends BaseGenericObjectPool * * @see GenericObjectPoolConfig */ - public void setConfig(final GenericObjectPoolConfig conf) { - super.setConfig(conf); + public void setConfig(final GenericObjectPoolConfig conf) { + setLifo(conf.getLifo()); setMaxIdle(conf.getMaxIdle()); setMinIdle(conf.getMinIdle()); setMaxTotal(conf.getMaxTotal()); + setMaxWaitMillis(conf.getMaxWaitMillis()); + setBlockWhenExhausted(conf.getBlockWhenExhausted()); + setTestOnCreate(conf.getTestOnCreate()); + setTestOnBorrow(conf.getTestOnBorrow()); + setTestOnReturn(conf.getTestOnReturn()); + setTestWhileIdle(conf.getTestWhileIdle()); + setNumTestsPerEvictionRun(conf.getNumTestsPerEvictionRun()); + setMinEvictableIdleTimeMillis(conf.getMinEvictableIdleTimeMillis()); + setTimeBetweenEvictionRunsMillis( + conf.getTimeBetweenEvictionRunsMillis()); + setSoftMinEvictableIdleTimeMillis( + conf.getSoftMinEvictableIdleTimeMillis()); + setEvictionPolicyClassName(conf.getEvictionPolicyClassName()); + setEvictorShutdownTimeoutMillis(conf.getEvictorShutdownTimeoutMillis()); } /** @@ -318,7 +326,6 @@ public class GenericObjectPool extends BaseGenericObjectPool * * @see AbandonedConfig */ - @SuppressWarnings("resource") // PrintWriter is managed elsewhere public void setAbandonedConfig(final AbandonedConfig abandonedConfig) { if (abandonedConfig == null) { this.abandonedConfig = null; @@ -335,7 +342,7 @@ public class GenericObjectPool extends BaseGenericObjectPool } /** - * Obtains a reference to the factory used to create, destroy and validate + * Obtain a reference to the factory used to create, destroy and validate * the objects used by this pool. * * @return the factory @@ -349,7 +356,6 @@ public class GenericObjectPool extends BaseGenericObjectPool * borrowObject}({@link #getMaxWaitMillis()}). *

    * {@inheritDoc} - *

    */ @Override public T borrowObject() throws Exception { @@ -357,43 +363,39 @@ public class GenericObjectPool extends BaseGenericObjectPool } /** - * Borrows an object from the pool using the specific waiting time which only + * Borrow an object from the pool using the specific waiting time which only * applies if {@link #getBlockWhenExhausted()} is true. *

    * If there is one or more idle instance available in the pool, then an * idle instance will be selected based on the value of {@link #getLifo()}, * activated and returned. If activation fails, or {@link #getTestOnBorrow() - * testOnBorrow} is set to {@code true} and validation fails, the + * testOnBorrow} is set to true and validation fails, the * instance is destroyed and the next available instance is examined. This * continues until either a valid instance is returned or there are no more * idle instances available. - *

    *

    * If there are no idle instances available in the pool, behavior depends on * the {@link #getMaxTotal() maxTotal}, (if applicable) * {@link #getBlockWhenExhausted()} and the value passed in to the - * {@code borrowMaxWaitMillis} parameter. If the number of instances - * checked out from the pool is less than {@code maxTotal,} a new + * borrowMaxWaitMillis parameter. If the number of instances + * checked out from the pool is less than maxTotal, a new * instance is created, activated and (if applicable) validated and returned - * to the caller. If validation fails, a {@code NoSuchElementException} + * to the caller. If validation fails, a NoSuchElementException * is thrown. - *

    *

    * If the pool is exhausted (no available idle instances and no capacity to * create new ones), this method will either block (if * {@link #getBlockWhenExhausted()} is true) or throw a - * {@code NoSuchElementException} (if + * NoSuchElementException (if * {@link #getBlockWhenExhausted()} is false). The length of time that this * method will block when {@link #getBlockWhenExhausted()} is true is - * determined by the value passed in to the {@code borrowMaxWaitMillis} + * determined by the value passed in to the borrowMaxWaitMillis * parameter. - *

    *

    * When the pool is exhausted, multiple calling threads may be * simultaneously blocked waiting for instances to become available. A * "fairness" algorithm has been implemented to ensure that threads receive * available instances in request arrival order. - *

    * * @param borrowMaxWaitMillis The time to wait in milliseconds for an object * to become available @@ -460,7 +462,7 @@ public class GenericObjectPool extends BaseGenericObjectPool factory.activateObject(p); } catch (final Exception e) { try { - destroy(p, DestroyMode.NORMAL); + destroy(p); } catch (final Exception e1) { // Ignore - activation failure is more important } @@ -472,7 +474,7 @@ public class GenericObjectPool extends BaseGenericObjectPool throw nsee; } } - if (p != null && getTestOnBorrow()) { + if (p != null && (getTestOnBorrow() || create && getTestOnCreate())) { boolean validate = false; Throwable validationThrowable = null; try { @@ -483,7 +485,7 @@ public class GenericObjectPool extends BaseGenericObjectPool } if (!validate) { try { - destroy(p, DestroyMode.NORMAL); + destroy(p); destroyedByBorrowValidationCount.incrementAndGet(); } catch (final Exception e) { // Ignore - validation failure is more important @@ -511,20 +513,17 @@ public class GenericObjectPool extends BaseGenericObjectPool * If {@link #getMaxIdle() maxIdle} is set to a positive value and the * number of idle instances has reached this value, the returning instance * is destroyed. - *

    *

    * If {@link #getTestOnReturn() testOnReturn} == true, the returning * instance is validated before being returned to the idle instance pool. In * this case, if validation fails, the instance is destroyed. - *

    *

    * Exceptions encountered destroying objects for any reason are swallowed * but notified via a {@link SwallowedExceptionListener}. - *

    */ @Override public void returnObject(final T obj) { - final PooledObject p = allObjects.get(new IdentityWrapper<>(obj)); + final PooledObject p = allObjects.get(new IdentityWrapper(obj)); if (p == null) { if (!isAbandonedConfig()) { @@ -534,23 +533,32 @@ public class GenericObjectPool extends BaseGenericObjectPool return; // Object was abandoned and removed } - markReturningState(p); + synchronized(p) { + final PooledObjectState state = p.getState(); + if (state != PooledObjectState.ALLOCATED) { + throw new IllegalStateException( + "Object has already been returned to this pool or is invalid"); + } + p.markReturning(); // Keep from being marked abandoned + } final long activeTime = p.getActiveTimeMillis(); - if (getTestOnReturn() && !factory.validateObject(p)) { - try { - destroy(p, DestroyMode.NORMAL); - } catch (final Exception e) { - swallowException(e); - } - try { - ensureIdle(1, false); - } catch (final Exception e) { - swallowException(e); + if (getTestOnReturn()) { + if (!factory.validateObject(p)) { + try { + destroy(p); + } catch (final Exception e) { + swallowException(e); + } + try { + ensureIdle(1, false); + } catch (final Exception e) { + swallowException(e); + } + updateStatsReturn(activeTime); + return; } - updateStatsReturn(activeTime); - return; } try { @@ -558,7 +566,7 @@ public class GenericObjectPool extends BaseGenericObjectPool } catch (final Exception e1) { swallowException(e1); try { - destroy(p, DestroyMode.NORMAL); + destroy(p); } catch (final Exception e) { swallowException(e); } @@ -579,12 +587,7 @@ public class GenericObjectPool extends BaseGenericObjectPool final int maxIdleSave = getMaxIdle(); if (isClosed() || maxIdleSave > -1 && maxIdleSave <= idleObjects.size()) { try { - destroy(p, DestroyMode.NORMAL); - } catch (final Exception e) { - swallowException(e); - } - try { - ensureIdle(1, false); + destroy(p); } catch (final Exception e) { swallowException(e); } @@ -608,8 +611,7 @@ public class GenericObjectPool extends BaseGenericObjectPool * {@inheritDoc} *

    * Activation of this method decrements the active count and attempts to - * destroy the instance, using the default (NORMAL) {@link DestroyMode}. - *

    + * destroy the instance. * * @throws Exception if an exception occurs destroying the * object @@ -617,24 +619,7 @@ public class GenericObjectPool extends BaseGenericObjectPool */ @Override public void invalidateObject(final T obj) throws Exception { - invalidateObject(obj, DestroyMode.NORMAL); - } - - /** - * {@inheritDoc} - *

    - * Activation of this method decrements the active count and attempts to - * destroy the instance, using the provided {@link DestroyMode}. - *

    - * - * @throws Exception if an exception occurs destroying the - * object - * @throws IllegalStateException if obj does not belong to this pool - * @since 2.9.0 - */ - @Override - public void invalidateObject(final T obj, final DestroyMode mode) throws Exception { - final PooledObject p = allObjects.get(new IdentityWrapper<>(obj)); + final PooledObject p = allObjects.get(new IdentityWrapper(obj)); if (p == null) { if (isAbandonedConfig()) { return; @@ -644,7 +629,7 @@ public class GenericObjectPool extends BaseGenericObjectPool } synchronized (p) { if (p.getState() != PooledObjectState.INVALID) { - destroy(p, mode); + destroy(p); } } ensureIdle(1, false); @@ -657,7 +642,6 @@ public class GenericObjectPool extends BaseGenericObjectPool * idle instance. *

    * Implementation notes: - *

    *
      *
    • This method does not destroy or effect in any way instances that are * checked out of the pool when it is invoked.
    • @@ -674,7 +658,7 @@ public class GenericObjectPool extends BaseGenericObjectPool while (p != null) { try { - destroy(p, DestroyMode.NORMAL); + destroy(p); } catch (final Exception e) { swallowException(e); } @@ -699,7 +683,6 @@ public class GenericObjectPool extends BaseGenericObjectPool * objects destroyed on return. *

      * Destroys idle instances in the pool by invoking {@link #clear()}. - *

      */ @Override public void close() { @@ -714,7 +697,7 @@ public class GenericObjectPool extends BaseGenericObjectPool // Stop the evictor before the pool is closed since evict() calls // assertOpen() - stopEvictor(); + startEvictor(-1L); closed = true; // This clear removes any idle objects @@ -732,7 +715,6 @@ public class GenericObjectPool extends BaseGenericObjectPool *

      * Successive activations of this method examine objects in sequence, * cycling through objects in oldest-to-youngest order. - *

      */ @Override public void evict() throws Exception { @@ -794,7 +776,7 @@ public class GenericObjectPool extends BaseGenericObjectPool } if (evict) { - destroy(underTest, DestroyMode.NORMAL); + destroy(underTest); destroyedByEvictorCount.incrementAndGet(); } else { if (testWhileIdle) { @@ -803,18 +785,18 @@ public class GenericObjectPool extends BaseGenericObjectPool factory.activateObject(underTest); active = true; } catch (final Exception e) { - destroy(underTest, DestroyMode.NORMAL); + destroy(underTest); destroyedByEvictorCount.incrementAndGet(); } if (active) { if (!factory.validateObject(underTest)) { - destroy(underTest, DestroyMode.NORMAL); + destroy(underTest); destroyedByEvictorCount.incrementAndGet(); } else { try { factory.passivateObject(underTest); } catch (final Exception e) { - destroy(underTest, DestroyMode.NORMAL); + destroy(underTest); destroyedByEvictorCount.incrementAndGet(); } } @@ -853,7 +835,6 @@ public class GenericObjectPool extends BaseGenericObjectPool *

      * If there are {@link #getMaxTotal()} objects already in circulation * or in process of being created, this method returns null. - *

      * * @return The new wrapped pooled object * @@ -866,9 +847,6 @@ public class GenericObjectPool extends BaseGenericObjectPool localMaxTotal = Integer.MAX_VALUE; } - final long localStartTimeMillis = System.currentTimeMillis(); - final long localMaxWaitTimeMillis = Math.max(getMaxWaitMillis(), 0); - // Flag that indicates if create should: // - TRUE: call the factory to create an object // - FALSE: return null @@ -892,7 +870,7 @@ public class GenericObjectPool extends BaseGenericObjectPool // bring the pool to capacity. Those calls might also // fail so wait until they complete and then re-test if // the pool is at capacity or not. - makeObjectCountLock.wait(localMaxWaitTimeMillis); + makeObjectCountLock.wait(); } } else { // The pool is not at capacity. Create a new object. @@ -900,13 +878,6 @@ public class GenericObjectPool extends BaseGenericObjectPool create = Boolean.TRUE; } } - - // Do not block more if maxWaitTimeMillis is set. - if (create == null && - (localMaxWaitTimeMillis > 0 && - System.currentTimeMillis() - localStartTimeMillis >= localMaxWaitTimeMillis)) { - create = Boolean.FALSE; - } } if (!create.booleanValue()) { @@ -916,11 +887,7 @@ public class GenericObjectPool extends BaseGenericObjectPool final PooledObject p; try { p = factory.makeObject(); - if (getTestOnCreate() && !factory.validateObject(p)) { - createCount.decrementAndGet(); - return null; - } - } catch (final Throwable e) { + } catch (final Exception e) { createCount.decrementAndGet(); throw e; } finally { @@ -933,11 +900,14 @@ public class GenericObjectPool extends BaseGenericObjectPool final AbandonedConfig ac = this.abandonedConfig; if (ac != null && ac.getLogAbandoned()) { p.setLogAbandoned(true); - p.setRequireFullStackTrace(ac.getRequireFullStackTrace()); + // TODO: in 3.0, this can use the method defined on PooledObject + if (p instanceof DefaultPooledObject) { + ((DefaultPooledObject) p).setRequireFullStackTrace(ac.getRequireFullStackTrace()); + } } createdCount.incrementAndGet(); - allObjects.put(new IdentityWrapper<>(p.getObject()), p); + allObjects.put(new IdentityWrapper(p.getObject()), p); return p; } @@ -945,17 +915,16 @@ public class GenericObjectPool extends BaseGenericObjectPool * Destroys a wrapped pooled object. * * @param toDestroy The wrapped pooled object to destroy - * @param mode DestroyMode context provided to the factory * * @throws Exception If the factory fails to destroy the pooled object * cleanly */ - private void destroy(final PooledObject toDestroy, final DestroyMode mode) throws Exception { + private void destroy(final PooledObject toDestroy) throws Exception { toDestroy.invalidate(); idleObjects.remove(toDestroy); - allObjects.remove(new IdentityWrapper<>(toDestroy.getObject())); + allObjects.remove(new IdentityWrapper(toDestroy.getObject())); try { - factory.destroyObject(toDestroy, mode); + factory.destroyObject(toDestroy); } finally { destroyedCount.incrementAndGet(); createCount.decrementAndGet(); @@ -974,7 +943,6 @@ public class GenericObjectPool extends BaseGenericObjectPool * or the total number of objects (idle, checked out, or being created) reaches * {@link #getMaxTotal()}. If {@code always} is false, no instances are created unless * there are threads waiting to check out instances from the pool. - *

      * * @param idleCount the number of idle instances desired * @param always true means create instances even if the pool has no threads waiting @@ -1007,7 +975,7 @@ public class GenericObjectPool extends BaseGenericObjectPool } /** - * Creates an object, and place it into the pool. addObject() is useful for + * Create an object, and place it into the pool. addObject() is useful for * "pre-loading" a pool with idle objects. *

      * If there is no capacity available to add to the pool, this is a no-op @@ -1025,7 +993,7 @@ public class GenericObjectPool extends BaseGenericObjectPool } /** - * Adds the provided wrapped pooled object to the set of idle objects for + * Add the provided wrapped pooled object to the set of idle objects for * this pool. The object must already be part of the pool. If {@code p} * is null, this is a no-op (no exception, but no impact on the pool). * @@ -1045,7 +1013,7 @@ public class GenericObjectPool extends BaseGenericObjectPool } /** - * Calculates the number of objects to test in a run of the idle object + * Calculate the number of objects to test in a run of the idle object * evictor. * * @return The number of objects to test for validity @@ -1060,18 +1028,17 @@ public class GenericObjectPool extends BaseGenericObjectPool } /** - * Recovers abandoned objects which have been checked out but + * Recover abandoned objects which have been checked out but * not used since longer than the removeAbandonedTimeout. * - * @param abandonedConfig The configuration to use to identify abandoned objects + * @param ac The configuration to use to identify abandoned objects */ - @SuppressWarnings("resource") // PrintWriter is managed elsewhere - private void removeAbandoned(final AbandonedConfig abandonedConfig) { + private void removeAbandoned(final AbandonedConfig ac) { // Generate a list of abandoned objects to remove final long now = System.currentTimeMillis(); final long timeout = - now - (abandonedConfig.getRemoveAbandonedTimeout() * 1000L); - final ArrayList> remove = new ArrayList<>(); + now - (ac.getRemoveAbandonedTimeout() * 1000L); + final ArrayList> remove = new ArrayList>(); final Iterator> it = allObjects.values().iterator(); while (it.hasNext()) { final PooledObject pooledObject = it.next(); @@ -1088,11 +1055,11 @@ public class GenericObjectPool extends BaseGenericObjectPool final Iterator> itr = remove.iterator(); while (itr.hasNext()) { final PooledObject pooledObject = itr.next(); - if (abandonedConfig.getLogAbandoned()) { - pooledObject.printStackTrace(abandonedConfig.getLogWriter()); + if (ac.getLogAbandoned()) { + pooledObject.printStackTrace(ac.getLogWriter()); } try { - invalidateObject(pooledObject.getObject(), DestroyMode.ABANDONED); + invalidateObject(pooledObject.getObject()); } catch (final Exception e) { e.printStackTrace(); } @@ -1104,9 +1071,9 @@ public class GenericObjectPool extends BaseGenericObjectPool @Override public void use(final T pooledObject) { - final AbandonedConfig abandonedCfg = this.abandonedConfig; - if (abandonedCfg != null && abandonedCfg.getUseUsageTracking()) { - final PooledObject wrapper = allObjects.get(new IdentityWrapper<>(pooledObject)); + final AbandonedConfig ac = this.abandonedConfig; + if (ac != null && ac.getUseUsageTracking()) { + final PooledObject wrapper = allObjects.get(new IdentityWrapper(pooledObject)); wrapper.use(); } } @@ -1117,7 +1084,7 @@ public class GenericObjectPool extends BaseGenericObjectPool private volatile String factoryType = null; /** - * Returns an estimate of the number of threads currently blocked waiting for + * Return an estimate of the number of threads currently blocked waiting for * an object from the pool. This is intended for monitoring only, not for * synchronization control. * @@ -1133,7 +1100,7 @@ public class GenericObjectPool extends BaseGenericObjectPool } /** - * Returns the type - including the specific type rather than the generic - + * Return the type - including the specific type rather than the generic - * of the factory. * * @return A string representation of the factory type @@ -1162,14 +1129,13 @@ public class GenericObjectPool extends BaseGenericObjectPool * JMX. That means it won't be invoked unless the explicitly requested * whereas all attributes will be automatically requested when viewing the * attributes for an object in a tool like JConsole. - *

      * * @return Information grouped on all the objects in the pool */ @Override public Set listAllObjects() { final Set result = - new HashSet<>(allObjects.size()); + new HashSet(allObjects.size()); for (final PooledObject p : allObjects.values()) { result.add(new DefaultPooledObjectInfo(p)); } @@ -1193,7 +1159,7 @@ public class GenericObjectPool extends BaseGenericObjectPool * wrappers used internally by the pool. */ private final Map, PooledObject> allObjects = - new ConcurrentHashMap<>(); + new ConcurrentHashMap, PooledObject>(); /* * The combined count of the currently created objects and those in the * process of being created. Under load, it may exceed {@link #_maxActive} @@ -1208,7 +1174,7 @@ public class GenericObjectPool extends BaseGenericObjectPool // JMX specific attributes private static final String ONAME_BASE = - "org.apache.commons.pool2:type=GenericObjectPool,name="; + "com.fr.third.org.apache.commons.pool2:type=GenericObjectPool,name="; // Additional configuration properties for abandoned object tracking private volatile AbandonedConfig abandonedConfig = null; diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericObjectPoolConfig.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericObjectPoolConfig.java index c4ecb72cc..fe1e8723d 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericObjectPoolConfig.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericObjectPoolConfig.java @@ -23,12 +23,10 @@ package com.fr.third.org.apache.commons.pool2.impl; *

      * This class is not thread-safe; it is only intended to be used to provide * attributes used when creating a pool. - *

      * - * @param Type of element pooled. * @since 2.0 */ -public class GenericObjectPoolConfig extends BaseObjectPoolConfig { +public class GenericObjectPoolConfig extends BaseObjectPoolConfig { /** * The default value for the {@code maxTotal} configuration attribute. @@ -135,11 +133,10 @@ public class GenericObjectPoolConfig extends BaseObjectPoolConfig { this.minIdle = minIdle; } - @SuppressWarnings("unchecked") @Override - public GenericObjectPoolConfig clone() { + public GenericObjectPoolConfig clone() { try { - return (GenericObjectPoolConfig) super.clone(); + return (GenericObjectPoolConfig) super.clone(); } catch (final CloneNotSupportedException e) { throw new AssertionError(); // Can't happen } diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericObjectPoolMXBean.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericObjectPoolMXBean.java index cca808d0c..724913216 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericObjectPoolMXBean.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericObjectPoolMXBean.java @@ -31,180 +31,149 @@ import java.util.Set; * @since 2.0 */ public interface GenericObjectPoolMXBean { - // Getters for basic configuration settings - /** * See {@link GenericObjectPool#getBlockWhenExhausted()} * @return See {@link GenericObjectPool#getBlockWhenExhausted()} */ boolean getBlockWhenExhausted(); - /** * See {@link GenericObjectPool#getLifo()} * @return See {@link GenericObjectPool#getLifo()} */ boolean getFairness(); - /** * See {@link GenericObjectPool#getFairness()} * @return See {@link GenericObjectPool#getFairness()} */ boolean getLifo(); - /** * See {@link GenericObjectPool#getMaxIdle()} * @return See {@link GenericObjectPool#getMaxIdle()} */ int getMaxIdle(); - /** * See {@link GenericObjectPool#getMaxTotal()} * @return See {@link GenericObjectPool#getMaxTotal()} */ int getMaxTotal(); - /** * See {@link GenericObjectPool#getMaxWaitMillis()} * @return See {@link GenericObjectPool#getMaxWaitMillis()} */ long getMaxWaitMillis(); - /** * See {@link GenericObjectPool#getMinEvictableIdleTimeMillis()} * @return See {@link GenericObjectPool#getMinEvictableIdleTimeMillis()} */ long getMinEvictableIdleTimeMillis(); - /** * See {@link GenericObjectPool#getMinIdle()} * @return See {@link GenericObjectPool#getMinIdle()} */ int getMinIdle(); - /** * See {@link GenericObjectPool#getNumActive()} * @return See {@link GenericObjectPool#getNumActive()} */ int getNumActive(); - /** * See {@link GenericObjectPool#getNumIdle()} * @return See {@link GenericObjectPool#getNumIdle()} */ int getNumIdle(); - /** * See {@link GenericObjectPool#getNumTestsPerEvictionRun()} * @return See {@link GenericObjectPool#getNumTestsPerEvictionRun()} */ int getNumTestsPerEvictionRun(); - /** * See {@link GenericObjectPool#getTestOnCreate()} * @return See {@link GenericObjectPool#getTestOnCreate()} * @since 2.2 */ boolean getTestOnCreate(); - /** * See {@link GenericObjectPool#getTestOnBorrow()} * @return See {@link GenericObjectPool#getTestOnBorrow()} */ boolean getTestOnBorrow(); - /** * See {@link GenericObjectPool#getTestOnReturn()} * @return See {@link GenericObjectPool#getTestOnReturn()} */ boolean getTestOnReturn(); - /** * See {@link GenericObjectPool#getTestWhileIdle()} * @return See {@link GenericObjectPool#getTestWhileIdle()} */ boolean getTestWhileIdle(); - /** * See {@link GenericObjectPool#getTimeBetweenEvictionRunsMillis()} * @return See {@link GenericObjectPool#getTimeBetweenEvictionRunsMillis()} */ long getTimeBetweenEvictionRunsMillis(); - /** * See {@link GenericObjectPool#isClosed()} * @return See {@link GenericObjectPool#isClosed()} */ boolean isClosed(); - // Getters for monitoring attributes - /** * See {@link GenericObjectPool#getBorrowedCount()} * @return See {@link GenericObjectPool#getBorrowedCount()} */ long getBorrowedCount(); - /** * See {@link GenericObjectPool#getReturnedCount()} * @return See {@link GenericObjectPool#getReturnedCount()} */ long getReturnedCount(); - /** * See {@link GenericObjectPool#getCreatedCount()} * @return See {@link GenericObjectPool#getCreatedCount()} */ long getCreatedCount(); - /** * See {@link GenericObjectPool#getDestroyedCount()} * @return See {@link GenericObjectPool#getDestroyedCount()} */ long getDestroyedCount(); - /** * See {@link GenericObjectPool#getDestroyedByEvictorCount()} * @return See {@link GenericObjectPool#getDestroyedByEvictorCount()} */ long getDestroyedByEvictorCount(); - /** * See {@link GenericObjectPool#getDestroyedByBorrowValidationCount()} * @return See {@link GenericObjectPool#getDestroyedByBorrowValidationCount()} */ long getDestroyedByBorrowValidationCount(); - /** * See {@link GenericObjectPool#getMeanActiveTimeMillis()} * @return See {@link GenericObjectPool#getMeanActiveTimeMillis()} */ long getMeanActiveTimeMillis(); - /** * See {@link GenericObjectPool#getMeanIdleTimeMillis()} * @return See {@link GenericObjectPool#getMeanIdleTimeMillis()} */ long getMeanIdleTimeMillis(); - /** * See {@link GenericObjectPool#getMeanBorrowWaitTimeMillis()} * @return See {@link GenericObjectPool#getMeanBorrowWaitTimeMillis()} */ long getMeanBorrowWaitTimeMillis(); - /** * See {@link GenericObjectPool#getMaxBorrowWaitTimeMillis()} * @return See {@link GenericObjectPool#getMaxBorrowWaitTimeMillis()} */ long getMaxBorrowWaitTimeMillis(); - /** * See {@link GenericObjectPool#getCreationStackTrace()} * @return See {@link GenericObjectPool#getCreationStackTrace()} */ String getCreationStackTrace(); - /** * See {@link GenericObjectPool#getNumWaiters()} * @return See {@link GenericObjectPool#getNumWaiters()} @@ -212,43 +181,36 @@ public interface GenericObjectPoolMXBean { int getNumWaiters(); // Getters for abandoned object removal configuration - /** * See {@link GenericObjectPool#isAbandonedConfig()} * @return See {@link GenericObjectPool#isAbandonedConfig()} */ boolean isAbandonedConfig(); - /** * See {@link GenericObjectPool#getLogAbandoned()} * @return See {@link GenericObjectPool#getLogAbandoned()} */ boolean getLogAbandoned(); - /** * See {@link GenericObjectPool#getRemoveAbandonedOnBorrow()} * @return See {@link GenericObjectPool#getRemoveAbandonedOnBorrow()} */ boolean getRemoveAbandonedOnBorrow(); - /** * See {@link GenericObjectPool#getRemoveAbandonedOnMaintenance()} * @return See {@link GenericObjectPool#getRemoveAbandonedOnMaintenance()} */ boolean getRemoveAbandonedOnMaintenance(); - /** * See {@link GenericObjectPool#getRemoveAbandonedTimeout()} * @return See {@link GenericObjectPool#getRemoveAbandonedTimeout()} */ int getRemoveAbandonedTimeout(); - /** * See {@link GenericObjectPool#getFactoryType()} * @return See {@link GenericObjectPool#getFactoryType()} */ - String getFactoryType(); - + public String getFactoryType(); /** * See {@link GenericObjectPool#listAllObjects()} * @return See {@link GenericObjectPool#listAllObjects()} diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/InterruptibleReentrantLock.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/InterruptibleReentrantLock.java index 2026c80e4..c8eac88a0 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/InterruptibleReentrantLock.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/InterruptibleReentrantLock.java @@ -26,7 +26,6 @@ import java.util.concurrent.locks.ReentrantLock; * class is intended for internal use only. *

      * This class is intended to be thread-safe. - *

      * * @since 2.0 */ diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/LinkedBlockingDeque.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/LinkedBlockingDeque.java index dde873de6..7fda0a1c9 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/LinkedBlockingDeque.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/LinkedBlockingDeque.java @@ -22,7 +22,6 @@ import java.util.Collection; import java.util.Deque; import java.util.Iterator; import java.util.NoSuchElementException; -import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; @@ -35,7 +34,6 @@ import java.util.concurrent.locks.Condition; * is equal to {@link Integer#MAX_VALUE}. Linked nodes are * dynamically created upon each insertion unless this would bring the * deque above capacity. - *

      * *

      Most operations run in constant time (ignoring time spent * blocking). Exceptions include {@link #remove(Object) remove}, @@ -43,17 +41,14 @@ import java.util.concurrent.locks.Condition; * #removeLastOccurrence removeLastOccurrence}, {@link #contains * contains}, {@link #iterator iterator.remove()}, and the bulk * operations, all of which run in linear time. - *

      * *

      This class and its iterator implement all of the * optional methods of the {@link Collection} and {@link * Iterator} interfaces. - *

      * *

      This class is a member of the * * Java Collections Framework. - *

      * * @param the type of elements held in this collection * @@ -225,7 +220,9 @@ class LinkedBlockingDeque extends AbstractQueue lock.lock(); // Never contended, but necessary for visibility try { for (final E e : c) { - Objects.requireNonNull(e); + if (e == null) { + throw new NullPointerException(); + } if (!linkLast(e)) { throw new IllegalStateException("Deque full"); } @@ -251,7 +248,7 @@ class LinkedBlockingDeque extends AbstractQueue return false; } final Node f = first; - final Node x = new Node<>(e, null, f); + final Node x = new Node(e, null, f); first = x; if (last == null) { last = x; @@ -276,7 +273,7 @@ class LinkedBlockingDeque extends AbstractQueue return false; } final Node l = last; - final Node x = new Node<>(e, l, null); + final Node x = new Node(e, l, null); last = x; if (first == null) { first = x; @@ -391,7 +388,9 @@ class LinkedBlockingDeque extends AbstractQueue */ @Override public boolean offerFirst(final E e) { - Objects.requireNonNull(e, "e"); + if (e == null) { + throw new NullPointerException(); + } lock.lock(); try { return linkFirst(e); @@ -405,7 +404,9 @@ class LinkedBlockingDeque extends AbstractQueue */ @Override public boolean offerLast(final E e) { - Objects.requireNonNull(e, "e"); + if (e == null) { + throw new NullPointerException(); + } lock.lock(); try { return linkLast(e); @@ -425,7 +426,9 @@ class LinkedBlockingDeque extends AbstractQueue * for space */ public void putFirst(final E e) throws InterruptedException { - Objects.requireNonNull(e, "e"); + if (e == null) { + throw new NullPointerException(); + } lock.lock(); try { while (!linkFirst(e)) { @@ -447,7 +450,9 @@ class LinkedBlockingDeque extends AbstractQueue * for space */ public void putLast(final E e) throws InterruptedException { - Objects.requireNonNull(e, "e"); + if (e == null) { + throw new NullPointerException(); + } lock.lock(); try { while (!linkLast(e)) { @@ -474,7 +479,9 @@ class LinkedBlockingDeque extends AbstractQueue */ public boolean offerFirst(final E e, final long timeout, final TimeUnit unit) throws InterruptedException { - Objects.requireNonNull(e, "e"); + if (e == null) { + throw new NullPointerException(); + } long nanos = unit.toNanos(timeout); lock.lockInterruptibly(); try { @@ -506,7 +513,9 @@ class LinkedBlockingDeque extends AbstractQueue */ public boolean offerLast(final E e, final long timeout, final TimeUnit unit) throws InterruptedException { - Objects.requireNonNull(e, "e"); + if (e == null) { + throw new NullPointerException(); + } long nanos = unit.toNanos(timeout); lock.lockInterruptibly(); try { @@ -892,7 +901,7 @@ class LinkedBlockingDeque extends AbstractQueue } /** - * Drains the queue to the specified collection. + * Empty the queue to the specified collection. * * @param c The collection to add the elements to * @@ -911,7 +920,7 @@ class LinkedBlockingDeque extends AbstractQueue } /** - * Drains no more than the specified number of elements from the queue to the + * Empty no more than the specified number of elements from the queue to the * specified collection. * * @param c collection to add the elements to @@ -927,7 +936,9 @@ class LinkedBlockingDeque extends AbstractQueue * @throws IllegalArgumentException if c is this instance */ public int drainTo(final Collection c, final int maxElements) { - Objects.requireNonNull(c, "c"); + if (c == null) { + throw new NullPointerException(); + } if (c == this) { throw new IllegalArgumentException(); } @@ -1136,7 +1147,7 @@ class LinkedBlockingDeque extends AbstractQueue public void clear() { lock.lock(); try { - for (Node f = first; f != null;) { + for (Node f = first; f != null; ) { f.item = null; final Node n = f.next; f.prev = null; @@ -1319,7 +1330,7 @@ class LinkedBlockingDeque extends AbstractQueue } /** - * Saves the state of this deque to a stream (that is, serialize it). + * Save the state of this deque to a stream (that is, serialize it). * * @serialData The capacity (int), followed by elements (each an * {@code Object}) in the proper order, followed by a null @@ -1343,7 +1354,7 @@ class LinkedBlockingDeque extends AbstractQueue } /** - * Reconstitutes this deque from a stream (that is, + * Reconstitute this deque from a stream (that is, * deserialize it). * @param s the stream */ @@ -1368,7 +1379,8 @@ class LinkedBlockingDeque extends AbstractQueue // Monitoring methods /** - * Returns true if there are threads waiting to take instances from this deque. See disclaimer on accuracy in + * Returns true if there are threads waiting to take instances from this deque. + * See disclaimer on accuracy in * {@link java.util.concurrent.locks.ReentrantLock#hasWaiters(Condition)}. * * @return true if there is at least one thread waiting on this deque's notEmpty condition. @@ -1383,8 +1395,8 @@ class LinkedBlockingDeque extends AbstractQueue } /** - * Returns the length of the queue of threads waiting to take instances from this deque. See disclaimer on accuracy - * in {@link java.util.concurrent.locks.ReentrantLock#getWaitQueueLength(Condition)}. + * Returns the length of the queue of threads waiting to take instances from this deque. + * See disclaimer on accuracy in {@link ReentrantLock#getWaitQueueLength(Condition)}. * * @return number of threads waiting on this deque's notEmpty condition. */ @@ -1398,8 +1410,9 @@ class LinkedBlockingDeque extends AbstractQueue } /** - * Interrupts the threads currently waiting to take an object from the pool. See disclaimer on accuracy in - * {@link java.util.concurrent.locks.ReentrantLock#getWaitingThreads(Condition)}. + * Interrupts the threads currently waiting to take an object from the pool. + * See disclaimer on accuracy in + * {@link ReentrantLock#getWaitingThreads(Condition)}. */ public void interuptTakeWaiters() { lock.lock(); diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/NoOpCallStack.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/NoOpCallStack.java index 5246a470a..b3f4df59c 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/NoOpCallStack.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/NoOpCallStack.java @@ -26,19 +26,13 @@ import java.io.PrintWriter; */ public class NoOpCallStack implements CallStack { - /** - * Singleton instance. - */ public static final CallStack INSTANCE = new NoOpCallStack(); - /** - * Constructs the singleton instance. - */ private NoOpCallStack() { } @Override - public boolean printStackTrace(final PrintWriter writer) { + public boolean printStackTrace(PrintWriter writer) { return false; } diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/PoolImplUtils.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/PoolImplUtils.java index 162e989c2..38c8441c6 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/PoolImplUtils.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/PoolImplUtils.java @@ -32,114 +32,84 @@ class PoolImplUtils { /** * Identifies the concrete type of object that an object factory creates. * - * @param factoryClass - * The factory to examine + * @param factory The factory to examine * * @return the type of object the factory creates */ @SuppressWarnings("rawtypes") - static Class getFactoryType(final Class factoryClass) { - final Class type = PooledObjectFactory.class; - final Object genericType = getGenericType(type, factoryClass); - if (genericType instanceof Integer) { - // POOL-324 com.fr.third.org.apache.commons.pool2.impl.GenericObjectPool.getFactoryType() throws - // java.lang.ClassCastException - // - // A bit hackish, but we must handle cases when getGenericType() does not return a concrete types. - final ParameterizedType pi = getParameterizedType(type, factoryClass); - if (pi != null) { - final Type[] bounds = ((TypeVariable) pi.getActualTypeArguments()[((Integer) genericType).intValue()]).getBounds(); - if (bounds != null && bounds.length > 0) { - final Type bound0 = bounds[0]; - if (bound0 instanceof Class) { - return (Class) bound0; - } - } - } - // last resort: Always return a Class - return Object.class; - } - return (Class) genericType; + static Class getFactoryType(final Class factory) { + return (Class) getGenericType(PooledObjectFactory.class, factory); } + /** - * Obtains the concrete type used by an implementation of an interface that uses a generic type. + * Obtain the concrete type used by an implementation of an interface that + * uses a generic type. * - * @param type - * The interface that defines a generic type - * @param clazz - * The class that implements the interface with a concrete type - * @param - * The interface type + * @param type The interface that defines a generic type + * @param clazz The class that implements the interface with a concrete type + * @param The interface type * * @return concrete type used by the implementation */ - private static Object getGenericType(final Class type, final Class clazz) { - if (type == null || clazz == null) { - // Error will be logged further up the call stack - return null; - } + private static Object getGenericType(final Class type, + final Class clazz) { // Look to see if this class implements the generic interface - final ParameterizedType pi = getParameterizedType(type, clazz); - if (pi != null) { - return getTypeParameter(clazz, pi.getActualTypeArguments()[0]); + + // Get all the interfaces + final Type[] interfaces = clazz.getGenericInterfaces(); + for (final Type iface : interfaces) { + // Only need to check interfaces that use generics + if (iface instanceof ParameterizedType) { + final ParameterizedType pi = (ParameterizedType) iface; + // Look for the generic interface + if (pi.getRawType() instanceof Class) { + if (type.isAssignableFrom((Class) pi.getRawType())) { + return getTypeParameter( + clazz, pi.getActualTypeArguments()[0]); + } + } + } } // Interface not found on this class. Look at the superclass. @SuppressWarnings("unchecked") - final Class superClass = (Class) clazz.getSuperclass(); + final + Class superClazz = + (Class) clazz.getSuperclass(); - final Object result = getGenericType(type, superClass); + final Object result = getGenericType(type, superClazz); if (result instanceof Class) { - // Superclass implements interface and defines explicit type for generic + // Superclass implements interface and defines explicit type for + // generic return result; } else if (result instanceof Integer) { - // Superclass implements interface and defines unknown type for generic + // Superclass implements interface and defines unknown type for + // generic // Map that unknown type to the generic types defined in this class - final ParameterizedType superClassType = (ParameterizedType) clazz.getGenericSuperclass(); - return getTypeParameter(clazz, superClassType.getActualTypeArguments()[((Integer) result).intValue()]); + final ParameterizedType superClassType = + (ParameterizedType) clazz.getGenericSuperclass(); + return getTypeParameter(clazz, + superClassType.getActualTypeArguments()[ + ((Integer) result).intValue()]); } else { // Error will be logged further up the call stack return null; } } - /** - * Gets the matching parameterized type or null. - * @param type - * The interface that defines a generic type. - * @param clazz - * The class that implements the interface with a concrete type. - * @param - * The interface type. - * @return the matching parameterized type or null. - */ - private static ParameterizedType getParameterizedType(final Class type, final Class clazz) { - for (final Type iface : clazz.getGenericInterfaces()) { - // Only need to check interfaces that use generics - if (iface instanceof ParameterizedType) { - final ParameterizedType pi = (ParameterizedType) iface; - // Look for the generic interface - if (pi.getRawType() instanceof Class && type.isAssignableFrom((Class) pi.getRawType())) { - return pi; - } - } - } - return null; - } /** - * For a generic parameter, return either the Class used or if the type is unknown, the index for the type in - * definition of the class + * For a generic parameter, return either the Class used or if the type + * is unknown, the index for the type in definition of the class * - * @param clazz - * defining class - * @param argType - * the type argument of interest + * @param clazz defining class + * @param argType the type argument of interest * - * @return An instance of {@link Class} representing the type used by the type parameter or an instance of - * {@link Integer} representing the index for the type in the definition of the defining class + * @return An instance of {@link Class} representing the type used by the + * type parameter or an instance of {@link Integer} representing + * the index for the type in the definition of the defining class */ private static Object getTypeParameter(final Class clazz, final Type argType) { if (argType instanceof Class) { diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/SecurityManagerCallStack.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/SecurityManagerCallStack.java index c11d0fd8c..c2ed5e804 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/SecurityManagerCallStack.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/SecurityManagerCallStack.java @@ -52,7 +52,12 @@ public class SecurityManagerCallStack implements CallStack { public SecurityManagerCallStack(final String messageFormat, final boolean useTimestamp) { this.messageFormat = messageFormat; this.dateFormat = useTimestamp ? new SimpleDateFormat(messageFormat) : null; - this.securityManager = AccessController.doPrivileged((PrivilegedAction) PrivateSecurityManager::new); + this.securityManager = AccessController.doPrivileged(new PrivilegedAction() { + @Override + public PrivateSecurityManager run() { + return new PrivateSecurityManager(); + } + }); } @Override @@ -97,7 +102,7 @@ public class SecurityManagerCallStack implements CallStack { */ private List>> getCallStack() { final Class[] classes = getClassContext(); - final List>> stack = new ArrayList<>(classes.length); + final List>> stack = new ArrayList>>(classes.length); for (final Class klass : classes) { stack.add(new WeakReference>(klass)); } diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/SoftReferenceObjectPool.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/SoftReferenceObjectPool.java index be2478723..e1a23ce0c 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/SoftReferenceObjectPool.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/SoftReferenceObjectPool.java @@ -29,10 +29,9 @@ import com.fr.third.org.apache.commons.pool2.PoolUtils; import com.fr.third.org.apache.commons.pool2.PooledObjectFactory; /** - * A {@link java.lang.ref.SoftReference SoftReference} based {@link ObjectPool}. + * A {@link SoftReference SoftReference} based {@link ObjectPool}. *

      * This class is intended to be thread-safe. - *

      * * @param * Type of element pooled in this pool. @@ -46,10 +45,10 @@ public class SoftReferenceObjectPool extends BaseObjectPool { /** * Queue of broken references that might be able to be removed from - * {@code _pool}. This is used to help {@link #getNumIdle()} be more + * _pool. This is used to help {@link #getNumIdle()} be more * accurate with minimal performance overhead. */ - private final ReferenceQueue refQueue = new ReferenceQueue<>(); + private final ReferenceQueue refQueue = new ReferenceQueue(); /** Count of instances that have been checkout out to pool clients */ private int numActive = 0; // @GuardedBy("this") @@ -63,14 +62,14 @@ public class SoftReferenceObjectPool extends BaseObjectPool { /** Idle references - waiting to be borrowed */ private final LinkedBlockingDeque> idleReferences = - new LinkedBlockingDeque<>(); + new LinkedBlockingDeque>(); /** All references - checked out or waiting to be borrowed. */ private final ArrayList> allReferences = - new ArrayList<>(); + new ArrayList>(); /** - * Create a {@code SoftReferenceObjectPool} with the specified factory. + * Create a SoftReferenceObjectPool with the specified factory. * * @param factory object factory to use. */ @@ -79,28 +78,28 @@ public class SoftReferenceObjectPool extends BaseObjectPool { } /** - * Borrows an object from the pool. If there are no idle instances available + * Borrow an object from the pool. If there are no idle instances available * in the pool, the configured factory's * {@link PooledObjectFactory#makeObject()} method is invoked to create a * new instance. *

      * All instances are {@link PooledObjectFactory#activateObject( - * com.fr.third.org.apache.commons.pool2.PooledObject) activated} + * org.apache.commons.pool2.PooledObject) activated} * and {@link PooledObjectFactory#validateObject( - * com.fr.third.org.apache.commons.pool2.PooledObject) + * org.apache.commons.pool2.PooledObject) * validated} before being returned by this method. If validation fails or * an exception occurs activating or validating an idle instance, the * failing instance is {@link PooledObjectFactory#destroyObject( - * com.fr.third.org.apache.commons.pool2.PooledObject) + * org.apache.commons.pool2.PooledObject) * destroyed} and another instance is retrieved from the pool, validated and * activated. This process continues until either the pool is empty or an * instance passes validation. If the pool is empty on activation or it does - * not contain any valid instances, the factory's {@code makeObject} + * not contain any valid instances, the factory's makeObject * method is used to create a new instance. If the created instance either * raises an exception on activation or fails validation, - * {@code NoSuchElementException} is thrown. Exceptions thrown by - * {@code MakeObject} are propagated to the caller; but other than - * {@code ThreadDeath} or {@code VirtualMachineError}, exceptions + * NoSuchElementException is thrown. Exceptions thrown by + * MakeObject are propagated to the caller; but other than + * ThreadDeath or VirtualMachineError, exceptions * generated by activation, validation or destroy methods are swallowed * silently. * @@ -128,7 +127,7 @@ public class SoftReferenceObjectPool extends BaseObjectPool { obj = factory.makeObject().getObject(); createCount++; // Do not register with the queue - ref = new PooledSoftReference<>(new SoftReference<>(obj)); + ref = new PooledSoftReference(new SoftReference(obj)); allReferences.add(ref); } else { ref = idleReferences.pollFirst(); @@ -137,7 +136,7 @@ public class SoftReferenceObjectPool extends BaseObjectPool { // a new, non-registered reference so we can still track this object // in allReferences ref.getReference().clear(); - ref.setReference(new SoftReference<>(obj)); + ref.setReference(new SoftReference(obj)); } if (null != factory && null != obj) { try { @@ -175,10 +174,10 @@ public class SoftReferenceObjectPool extends BaseObjectPool { *

        *
      • the pool is closed
      • *
      • {@link PooledObjectFactory#validateObject( - * com.fr.third.org.apache.commons.pool2.PooledObject) validation} fails + * org.apache.commons.pool2.PooledObject) validation} fails *
      • *
      • {@link PooledObjectFactory#passivateObject( - * com.fr.third.org.apache.commons.pool2.PooledObject) passivation} + * org.apache.commons.pool2.PooledObject) passivation} * throws an exception
      • *
      * Exceptions passivating or destroying instances are silently swallowed. @@ -186,8 +185,6 @@ public class SoftReferenceObjectPool extends BaseObjectPool { * * @param obj * instance to return to the pool - * @throws IllegalArgumentException - * if obj is not currently part of this pool */ @Override public synchronized void returnObject(final T obj) throws Exception { @@ -246,19 +243,19 @@ public class SoftReferenceObjectPool extends BaseObjectPool { } /** - * Creates an object, and places it into the pool. addObject() is useful for + * Create an object, and place it into the pool. addObject() is useful for * "pre-loading" a pool with idle objects. *

      * Before being added to the pool, the newly created instance is * {@link PooledObjectFactory#validateObject( - * com.fr.third.org.apache.commons.pool2.PooledObject) validated} and + * org.apache.commons.pool2.PooledObject) validated} and * {@link PooledObjectFactory#passivateObject( - * com.fr.third.org.apache.commons.pool2.PooledObject) passivated}. If + * org.apache.commons.pool2.PooledObject) passivated}. If * validation fails, the new instance is * {@link PooledObjectFactory#destroyObject( - * com.fr.third.org.apache.commons.pool2.PooledObject) destroyed}. Exceptions - * generated by the factory {@code makeObject} or - * {@code passivate} are propagated to the caller. Exceptions + * org.apache.commons.pool2.PooledObject) destroyed}. Exceptions + * generated by the factory makeObject or + * passivate are propagated to the caller. Exceptions * destroying instances are silently swallowed. * * @throws IllegalStateException @@ -277,8 +274,8 @@ public class SoftReferenceObjectPool extends BaseObjectPool { final T obj = factory.makeObject().getObject(); createCount++; // Create and register with the queue - final PooledSoftReference ref = new PooledSoftReference<>( - new SoftReference<>(obj, refQueue)); + final PooledSoftReference ref = new PooledSoftReference( + new SoftReference(obj, refQueue)); allReferences.add(ref); boolean success = true; @@ -316,7 +313,7 @@ public class SoftReferenceObjectPool extends BaseObjectPool { } /** - * Returns the number of instances currently borrowed from this pool. + * Return the number of instances currently borrowed from this pool. * * @return the number of instances currently borrowed from this pool */ @@ -348,7 +345,7 @@ public class SoftReferenceObjectPool extends BaseObjectPool { } /** - * Closes this pool, and frees any resources associated with it. Invokes + * Close this pool, and free any resources associated with it. Invokes * {@link #clear()} to destroy and remove instances in the pool. *

      * Calling {@link #addObject} or {@link #borrowObject} after invoking this @@ -385,7 +382,7 @@ public class SoftReferenceObjectPool extends BaseObjectPool { } /** - * Finds the PooledSoftReference in allReferences that points to obj. + * Find the PooledSoftReference in allReferences that points to obj. * * @param obj returning object * @return PooledSoftReference wrapping a soft reference to obj @@ -402,7 +399,7 @@ public class SoftReferenceObjectPool extends BaseObjectPool { } /** - * Destroys a {@code PooledSoftReference} and removes it from the idle and all + * Destroy a {@code PooledSoftReference} and remove it from the idle and all * references pools. * * @param toDestroy PooledSoftReference to destroy diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/package.html b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/package.html index 8f9c03fdb..98aefd78c 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/package.html +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/package.html @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. --> + Package Documentation for com.fr.third.org.apache.commons.pool2.impl diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/CglibProxySource.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/CglibProxySource.java index f6f388cd8..5a8f98b2f 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/CglibProxySource.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/CglibProxySource.java @@ -47,7 +47,7 @@ public class CglibProxySource implements ProxySource { enhancer.setSuperclass(superclass); final CglibProxyHandler proxyInterceptor = - new CglibProxyHandler<>(pooledObject, usageTracking); + new CglibProxyHandler(pooledObject, usageTracking); enhancer.setCallback(proxyInterceptor); @SuppressWarnings("unchecked") diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/JdkProxySource.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/JdkProxySource.java index d031d5fd4..26f6357ae 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/JdkProxySource.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/JdkProxySource.java @@ -53,7 +53,7 @@ public class JdkProxySource implements ProxySource { @SuppressWarnings("unchecked") final T proxy = (T) Proxy.newProxyInstance(classLoader, interfaces, - new JdkProxyHandler<>(pooledObject, usageTracking)); + new JdkProxyHandler(pooledObject, usageTracking)); return proxy; } diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/ProxiedKeyedObjectPool.java b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/ProxiedKeyedObjectPool.java index f471bb5f0..5adf20997 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/ProxiedKeyedObjectPool.java +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/ProxiedKeyedObjectPool.java @@ -32,9 +32,9 @@ import com.fr.third.org.apache.commons.pool2.UsageTracking; * * @since 2.0 */ -public class ProxiedKeyedObjectPool implements KeyedObjectPool { +public class ProxiedKeyedObjectPool implements KeyedObjectPool { - private final KeyedObjectPool pool; + private final KeyedObjectPool pool; private final ProxySource proxySource; @@ -44,7 +44,7 @@ public class ProxiedKeyedObjectPool implements KeyedObjectPool { * @param pool The object pool to wrap * @param proxySource The source of the proxy objects */ - public ProxiedKeyedObjectPool(final KeyedObjectPool pool, + public ProxiedKeyedObjectPool(final KeyedObjectPool pool, final ProxySource proxySource) { this.pool = pool; this.proxySource = proxySource; diff --git a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/package.html b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/package.html index ec3f7bde5..5e4fbae0e 100644 --- a/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/package.html +++ b/fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/package.html @@ -16,7 +16,7 @@ --> - Package Documentation for com.fr.third.org.apache.commons.pool2.proxy + Package Documentation for org.apache.commons.pool2.proxy

      diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/AccessControlLogEntry.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/AccessControlLogEntry.java deleted file mode 100644 index 5c1cb9081..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/AccessControlLogEntry.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.fr.third.redis.clients.jedis; - -import java.io.Serializable; -import java.util.*; - -/** - * This class holds information about an Access Control Log entry (returned by ACL LOG command) They - * can be access via getters. For future purpose there is also {@link #getlogEntry} method that - * returns a generic {@code Map} - in case where more info is returned from a server - */ -public class AccessControlLogEntry implements Serializable { - - private static final long serialVersionUID = 1L; - - public static final String COUNT = "count"; - public static final String REASON = "reason"; - public static final String CONTEXT = "context"; - public static final String OBJECT = "object"; - public static final String USERNAME = "username"; - public static final String AGE_SECONDS = "age-seconds"; - public static final String CLIENT_INFO = "client-info"; - - private long count; - private final String reason; - private final String context; - private final String object; - private final String username; - private final String ageSeconds; - private final Map clientInfo; - private final Map logEntry; - - public AccessControlLogEntry(Map map) { - count = (long) map.get(COUNT); - reason = (String) map.get(REASON); - context = (String) map.get(CONTEXT); - object = (String) map.get(OBJECT); - username = (String) map.get(USERNAME); - ageSeconds = (String) map.get(AGE_SECONDS); - clientInfo = getMapFromRawClientInfo((String) map.get(CLIENT_INFO)); - logEntry = map; - } - - public long getCount() { - return count; - } - - public String getReason() { - return reason; - } - - public String getContext() { - return context; - } - - public String getObject() { - return object; - } - - public String getUsername() { - return username; - } - - public String getAgeSeconds() { - return ageSeconds; - } - - public Map getClientInfo() { - return clientInfo; - } - - /** - * @return Generic map containing all key-value pairs returned by the server - */ - public Map getlogEntry() { - return logEntry; - } - - /** - * Convert the client-info string into a Map of String. When the value is empty, the value in the - * map is set to an empty string The key order is maintained to reflect the string return by Redis - * @param clientInfo - * @return A Map with all client info - */ - private Map getMapFromRawClientInfo(String clientInfo) { - String[] entries = clientInfo.split(" "); - Map clientInfoMap = new LinkedHashMap<>(entries.length); - for (String entry : entries) { - String[] kvArray = entry.split("="); - clientInfoMap.put(kvArray[0], (kvArray.length == 2) ? kvArray[1] : ""); - } - return clientInfoMap; - } - - @Override - public String toString() { - return "AccessControlLogEntry{" + "count=" + count + ", reason='" + reason + '\'' - + ", context='" + context + '\'' + ", object='" + object + '\'' + ", username='" + username - + '\'' + ", ageSeconds='" + ageSeconds + '\'' + ", clientInfo=" + clientInfo + '}'; - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/AccessControlUser.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/AccessControlUser.java deleted file mode 100644 index 672b497d2..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/AccessControlUser.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.fr.third.redis.clients.jedis; - -import java.util.ArrayList; -import java.util.List; - -public class AccessControlUser { - - private final List flags = new ArrayList<>(); - private final List keys = new ArrayList<>(); - private final List passwords = new ArrayList<>(); - private String commands; - - public AccessControlUser() { - } - - public void addFlag(String flag) { - flags.add(flag); - } - - public List getFlags() { - return flags; - } - - public void addKey(String key) { - keys.add(key); - } - - public List getKeys() { - return keys; - } - - public void addPassword(String password) { - passwords.add(password); - } - - public List getPassword() { - return passwords; - } - - public String getCommands() { - return commands; - } - - public void setCommands(String commands) { - this.commands = commands; - } - - @Override - public String toString() { - return "AccessControlUser{" + "flags=" + flags + ", keys=" + keys + ", passwords=" + passwords - + ", commands='" + commands + '\'' + '}'; - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryClient.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryClient.java index 738ca1d30..e534330ae 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryClient.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryClient.java @@ -2,41 +2,37 @@ package com.fr.third.redis.clients.jedis; import static com.fr.third.redis.clients.jedis.Protocol.toByteArray; import static com.fr.third.redis.clients.jedis.Protocol.Command.*; -import static com.fr.third.redis.clients.jedis.Protocol.Command.EXISTS; -import static com.fr.third.redis.clients.jedis.Protocol.Command.GET; -import static com.fr.third.redis.clients.jedis.Protocol.Command.INCR; -import static com.fr.third.redis.clients.jedis.Protocol.Command.KEYS; -import static com.fr.third.redis.clients.jedis.Protocol.Command.PING; -import static com.fr.third.redis.clients.jedis.Protocol.Command.PSUBSCRIBE; -import static com.fr.third.redis.clients.jedis.Protocol.Command.PUNSUBSCRIBE; -import static com.fr.third.redis.clients.jedis.Protocol.Command.SAVE; -import static com.fr.third.redis.clients.jedis.Protocol.Command.SET; -import static com.fr.third.redis.clients.jedis.Protocol.Command.SUBSCRIBE; -import static com.fr.third.redis.clients.jedis.Protocol.Command.TIME; -import static com.fr.third.redis.clients.jedis.Protocol.Command.UNSUBSCRIBE; -import static com.fr.third.redis.clients.jedis.Protocol.Keyword.*; - -import java.util.*; +import static com.fr.third.redis.clients.jedis.Protocol.Keyword.ENCODING; +import static com.fr.third.redis.clients.jedis.Protocol.Keyword.IDLETIME; +import static com.fr.third.redis.clients.jedis.Protocol.Keyword.LEN; +import static com.fr.third.redis.clients.jedis.Protocol.Keyword.LIMIT; +import static com.fr.third.redis.clients.jedis.Protocol.Keyword.NO; +import static com.fr.third.redis.clients.jedis.Protocol.Keyword.ONE; +import static com.fr.third.redis.clients.jedis.Protocol.Keyword.REFCOUNT; +import static com.fr.third.redis.clients.jedis.Protocol.Keyword.RESET; +import static com.fr.third.redis.clients.jedis.Protocol.Keyword.STORE; +import static com.fr.third.redis.clients.jedis.Protocol.Keyword.WITHSCORES; + +import java.util.ArrayList; +import java.util.List; +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 com.fr.third.redis.clients.jedis.Protocol.Command; import com.fr.third.redis.clients.jedis.Protocol.Keyword; -import com.fr.third.redis.clients.jedis.args.ListDirection; -import com.fr.third.redis.clients.jedis.args.FlushMode; -import com.fr.third.redis.clients.jedis.args.UnblockType; -import com.fr.third.redis.clients.jedis.params.*; -import com.fr.third.redis.clients.jedis.util.SafeEncoder; +import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; +import com.fr.third.redis.clients.jedis.params.SetParams; +import com.fr.third.redis.clients.jedis.params.ZAddParams; +import com.fr.third.redis.clients.jedis.params.ZIncrByParams; public class BinaryClient extends Connection { private boolean isInMulti; - @Deprecated - private String user; - @Deprecated private String password; private int db; @@ -47,12 +43,6 @@ public class BinaryClient extends Connection { 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); } @@ -61,34 +51,16 @@ public class BinaryClient extends Connection { 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; } @@ -97,46 +69,34 @@ public class BinaryClient extends Connection { 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; + private 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 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; } - /** - * @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) { + if (password != null) { auth(password); getStatusCodeReply(); } @@ -147,41 +107,6 @@ public class BinaryClient extends Connection { } } - @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); } @@ -202,14 +127,6 @@ public class BinaryClient extends Connection { 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); @@ -235,10 +152,6 @@ public class BinaryClient extends Connection { sendCommand(FLUSHDB); } - public void flushDB(FlushMode flushMode) { - sendCommand(FLUSHDB, flushMode.getRaw()); - } - public void keys(final byte[] pattern) { sendCommand(KEYS, pattern); } @@ -259,18 +172,10 @@ public class BinaryClient extends Connection { 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)); } @@ -299,10 +204,6 @@ public class BinaryClient extends Connection { sendCommand(FLUSHALL); } - public void flushAll(FlushMode flushMode) { - sendCommand(FLUSHALL, flushMode.getRaw()); - } - public void getSet(final byte[] key, final byte[] value) { sendCommand(GETSET, key, value); } @@ -315,18 +216,10 @@ public class BinaryClient extends Connection { 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); } @@ -388,7 +281,7 @@ public class BinaryClient extends Connection { } public void hmset(final byte[] key, final Map hash) { - final List params = new ArrayList<>(); + final List params = new ArrayList(); params.add(key); for (final Entry entry : hash.entrySet()) { @@ -430,18 +323,6 @@ public class BinaryClient extends Connection { 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)); } @@ -478,32 +359,10 @@ public class BinaryClient extends Connection { 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); } @@ -540,10 +399,6 @@ public class BinaryClient extends Connection { 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); } @@ -582,7 +437,7 @@ public class BinaryClient extends Connection { } public void zadd(final byte[] key, final Map scoreMembers) { - ArrayList args = new ArrayList<>(scoreMembers.size() * 2 + 1); + ArrayList args = new ArrayList(scoreMembers.size() * 2 + 1); args.add(key); args.addAll(convertScoreMembersToByteArrays(scoreMembers)); @@ -600,26 +455,6 @@ public class BinaryClient extends Connection { 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)); } @@ -651,23 +486,11 @@ public class BinaryClient extends Connection { } public void zrangeWithScores(final byte[] key, final long start, final long stop) { - sendCommand(ZRANGE, key, toByteArray(start), toByteArray(stop), WITHSCORES.getRaw()); + sendCommand(ZRANGE, key, toByteArray(start), toByteArray(stop), WITHSCORES.raw); } 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()); + sendCommand(ZREVRANGE, key, toByteArray(start), toByteArray(stop), WITHSCORES.raw); } public void zcard(final byte[] key) { @@ -678,26 +501,6 @@ public class BinaryClient extends Connection { 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; @@ -730,43 +533,36 @@ public class BinaryClient extends Connection { } public void sort(final byte[] key, final SortingParams sortingParameters) { - final List args = new ArrayList<>(); + final List args = new ArrayList(); args.add(key); args.addAll(sortingParameters.getParams()); sendCommand(SORT, args.toArray(new byte[args.size()][])); } + public void blpop(final byte[][] args) { + sendCommand(BLPOP, args); + } + + public void blpop(final int timeout, final byte[]... keys) { + final List args = new ArrayList(); + for (final byte[] arg : keys) { + args.add(arg); + } + args.add(Protocol.toByteArray(timeout)); + blpop(args.toArray(new byte[args.size()][])); + } + public void sort(final byte[] key, final SortingParams sortingParameters, final byte[] dstkey) { - final List args = new ArrayList<>(); + final List args = new ArrayList(); args.add(key); args.addAll(sortingParameters.getParams()); - args.add(STORE.getRaw()); + args.add(STORE.raw); 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)); + sendCommand(SORT, key, STORE.raw, dstkey); } public void brpop(final byte[][] args) { @@ -774,35 +570,12 @@ public class BinaryClient extends Connection { } 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; + final List args = new ArrayList(); + for (final byte[] arg : keys) { + args.add(arg); + } + args.add(Protocol.toByteArray(timeout)); + brpop(args.toArray(new byte[args.size()][])); } public void auth(final String password) { @@ -810,12 +583,6 @@ public class BinaryClient extends Connection { 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); } @@ -874,66 +641,64 @@ public class BinaryClient extends Connection { 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)); + sendCommand(ZRANGEBYSCORE, key, toByteArray(min), toByteArray(max), LIMIT.raw, 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)); + sendCommand(ZREVRANGEBYSCORE, key, toByteArray(max), toByteArray(min), LIMIT.raw, 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()); + sendCommand(ZRANGEBYSCORE, key, toByteArray(min), toByteArray(max), WITHSCORES.raw); } public void zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { - sendCommand(ZREVRANGEBYSCORE, key, toByteArray(max), toByteArray(min), WITHSCORES.getRaw()); + sendCommand(ZREVRANGEBYSCORE, key, toByteArray(max), toByteArray(min), WITHSCORES.raw); } 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()); + sendCommand(ZRANGEBYSCORE, key, toByteArray(min), toByteArray(max), LIMIT.raw, toByteArray(offset), + toByteArray(count), WITHSCORES.raw); } 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()); + sendCommand(ZREVRANGEBYSCORE, key, toByteArray(max), toByteArray(min), LIMIT.raw, toByteArray(offset), + toByteArray(count), WITHSCORES.raw); } 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)); + sendCommand(ZRANGEBYSCORE, key, min, max, LIMIT.raw, 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)); + sendCommand(ZREVRANGEBYSCORE, key, max, min, LIMIT.raw, toByteArray(offset), toByteArray(count)); } public void zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max) { - sendCommand(ZRANGEBYSCORE, key, min, max, WITHSCORES.getRaw()); + sendCommand(ZRANGEBYSCORE, key, min, max, WITHSCORES.raw); } public void zrevrangeByScoreWithScores(final byte[] key, final byte[] max, final byte[] min) { - sendCommand(ZREVRANGEBYSCORE, key, max, min, WITHSCORES.getRaw()); + sendCommand(ZREVRANGEBYSCORE, key, max, min, WITHSCORES.raw); } 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()); + sendCommand(ZRANGEBYSCORE, key, min, max, LIMIT.raw, toByteArray(offset), toByteArray(count), + WITHSCORES.raw); } 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()); + sendCommand(ZREVRANGEBYSCORE, key, max, min, LIMIT.raw, toByteArray(offset), + toByteArray(count), WITHSCORES.raw); } public void zremrangeByRank(final byte[] key, final long start, final long stop) { @@ -948,58 +713,32 @@ public class BinaryClient extends Connection { 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<>(); + final List args = new ArrayList(); args.add(dstkey); args.add(Protocol.toByteArray(sets.length)); - Collections.addAll(args, sets); - + for (final byte[] set : sets) { + args.add(set); + } 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<>(); + final List args = new ArrayList(); args.add(dstkey); args.add(Protocol.toByteArray(sets.length)); - Collections.addAll(args, sets); - + for (final byte[] set : sets) { + args.add(set); + } args.addAll(params.getParams()); sendCommand(ZINTERSTORE, args.toArray(new byte[args.size()][])); } @@ -1014,7 +753,7 @@ public class BinaryClient extends Connection { 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)); + sendCommand(ZRANGEBYLEX, key, min, max, LIMIT.raw, toByteArray(offset), toByteArray(count)); } public void zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min) { @@ -1023,8 +762,7 @@ public class BinaryClient extends Connection { 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)); + sendCommand(ZREVRANGEBYLEX, key, max, min, LIMIT.raw, toByteArray(offset), toByteArray(count)); } public void zremrangeByLex(final byte[] key, final byte[] min, final byte[] max) { @@ -1068,25 +806,21 @@ public class BinaryClient extends Connection { } public void slaveofNoOne() { - sendCommand(SLAVEOF, NO.getRaw(), ONE.getRaw()); + sendCommand(SLAVEOF, NO.raw, ONE.raw); } public void configGet(final byte[] pattern) { - sendCommand(CONFIG, Keyword.GET.getRaw(), pattern); + sendCommand(CONFIG, Keyword.GET.raw, pattern); } public void configSet(final byte[] parameter, final byte[] value) { - sendCommand(CONFIG, Keyword.SET.getRaw(), parameter, value); + sendCommand(CONFIG, Keyword.SET.raw, parameter, value); } public void strlen(final byte[] key) { sendCommand(STRLEN, key); } - /** - * @deprecated This will be removed in next major release. - */ - @Deprecated public void sync() { sendCommand(SYNC); } @@ -1121,11 +855,11 @@ public class BinaryClient extends Connection { } public void configResetStat() { - sendCommand(CONFIG, Keyword.RESETSTAT.getRaw()); + sendCommand(CONFIG, Keyword.RESETSTAT.raw); } public void configRewrite() { - sendCommand(CONFIG, Keyword.REWRITE.getRaw()); + sendCommand(CONFIG, Keyword.REWRITE.raw); } public void setbit(final byte[] key, final long offset, final byte[] value) { @@ -1141,7 +875,7 @@ public class BinaryClient extends Connection { } public void bitpos(final byte[] key, final boolean value, final BitPosParams params) { - final List args = new ArrayList<>(); + final List args = new ArrayList(); args.add(key); args.add(toByteArray(value)); args.addAll(params.getParams()); @@ -1156,6 +890,26 @@ public class BinaryClient extends Connection { sendCommand(GETRANGE, key, toByteArray(startOffset), toByteArray(endOffset)); } + public int getDB() { + return db; + } + + @Override + public void disconnect() { + db = 0; + super.disconnect(); + } + + @Override + public void close() { + db = 0; + super.close(); + } + + public void resetState() { + if (isInWatch()) unwatch(); + } + public void eval(final byte[] script, final byte[] keyCount, final byte[][] params) { sendCommand(EVAL, joinParameters(script, keyCount, params)); } @@ -1173,59 +927,47 @@ public class BinaryClient extends Connection { } public void scriptFlush() { - sendCommand(SCRIPT, Keyword.FLUSH.getRaw()); - } - - public void scriptFlush(FlushMode flushMode) { - sendCommand(SCRIPT, Keyword.FLUSH.getRaw(), flushMode.getRaw()); + sendCommand(SCRIPT, Keyword.FLUSH.raw); } public void scriptExists(final byte[]... sha1) { - sendCommand(SCRIPT, joinParameters(Keyword.EXISTS.getRaw(), sha1)); + sendCommand(SCRIPT, joinParameters(Keyword.EXISTS.raw, sha1)); } public void scriptLoad(final byte[] script) { - sendCommand(SCRIPT, Keyword.LOAD.getRaw(), script); + sendCommand(SCRIPT, Keyword.LOAD.raw, script); } public void scriptKill() { - sendCommand(SCRIPT, Keyword.KILL.getRaw()); + sendCommand(SCRIPT, Keyword.KILL.raw); } public void slowlogGet() { - sendCommand(SLOWLOG, Keyword.GET.getRaw()); + sendCommand(SLOWLOG, Keyword.GET.raw); } public void slowlogGet(final long entries) { - sendCommand(SLOWLOG, Keyword.GET.getRaw(), toByteArray(entries)); + sendCommand(SLOWLOG, Keyword.GET.raw, toByteArray(entries)); } public void slowlogReset() { - sendCommand(SLOWLOG, RESET.getRaw()); + sendCommand(SLOWLOG, RESET.raw); } public void slowlogLen() { - sendCommand(SLOWLOG, LEN.getRaw()); + sendCommand(SLOWLOG, LEN.raw); } public void objectRefcount(final byte[] key) { - sendCommand(OBJECT, REFCOUNT.getRaw(), key); + sendCommand(OBJECT, REFCOUNT.raw, key); } public void objectIdletime(final byte[] key) { - sendCommand(OBJECT, IDLETIME.getRaw(), key); + sendCommand(OBJECT, IDLETIME.raw, 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); + sendCommand(OBJECT, ENCODING.raw, key); } public void bitcount(final byte[] key) { @@ -1248,42 +990,10 @@ public class BinaryClient extends Connection { 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 #restoreReplace(byte[], long, byte[])}. - */ - @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)); } @@ -1304,99 +1014,30 @@ public class BinaryClient extends Connection { 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 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 clientKill(final byte[] client) { + sendCommand(CLIENT, Keyword.KILL.raw, client); } public void clientGetname() { - sendCommand(CLIENT, Keyword.GETNAME.getRaw()); + sendCommand(CLIENT, Keyword.GETNAME.raw); } public void clientList() { - sendCommand(CLIENT, Keyword.LIST.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()); + sendCommand(CLIENT, Keyword.LIST.raw); } 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()); - } + sendCommand(CLIENT, Keyword.SETNAME.raw, name); } public void time() { sendCommand(TIME); } - public void migrate(final String host, final int port, final byte[] key, final int destinationDb, + public void migrate(final byte[] 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); + sendCommand(MIGRATE, host, toByteArray(port), key, toByteArray(destinationDb), + toByteArray(timeout)); } public void hincrByFloat(final byte[] key, final byte[] field, final double increment) { @@ -1404,14 +1045,14 @@ public class BinaryClient extends Connection { } public void scan(final byte[] cursor, final ScanParams params) { - final List args = new ArrayList<>(); + final List args = new ArrayList(); args.add(cursor); args.addAll(params.getParams()); 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<>(); + final List args = new ArrayList(); args.add(key); args.add(cursor); args.addAll(params.getParams()); @@ -1419,7 +1060,7 @@ public class BinaryClient extends Connection { } public void sscan(final byte[] key, final byte[] cursor, final ScanParams params) { - final List args = new ArrayList<>(); + final List args = new ArrayList(); args.add(key); args.add(cursor); args.addAll(params.getParams()); @@ -1427,7 +1068,7 @@ public class BinaryClient extends Connection { } public void zscan(final byte[] key, final byte[] cursor, final ScanParams params) { - final List args = new ArrayList<>(); + final List args = new ArrayList(); args.add(key); args.add(cursor); args.addAll(params.getParams()); @@ -1466,31 +1107,26 @@ public class BinaryClient extends Connection { sendCommand(READONLY); } - public void geoadd(final byte[] key, final double longitude, final double latitude, - final byte[] member) { + 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); + List args = new ArrayList(memberCoordinateMap.size() * 3 + 1); + args.add(key); args.addAll(convertGeoCoordinateMapToByteArrays(memberCoordinateMap)); byte[][] argsArray = new byte[args.size()][]; args.toArray(argsArray); - sendCommand(GEOADD, params.getByteParams(key, argsArray)); + sendCommand(GEOADD, 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) { + public void geodist(final byte[] key, final byte[] member1, final byte[] member2, final GeoUnit unit) { sendCommand(GEODIST, key, member1, member2, unit.raw); } @@ -1502,80 +1138,42 @@ public class BinaryClient extends Connection { sendCommand(GEOPOS, joinParameters(key, members)); } - public void georadius(final byte[] key, final double longitude, final double latitude, - final double radius, final GeoUnit unit) { + 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) { + 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) { + 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) { + 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); + sendCommand(MODULE, Keyword.LOAD.raw, path); } public void moduleList() { - sendCommand(MODULE, Keyword.LIST.getRaw()); + sendCommand(MODULE, Keyword.LIST.raw); } public void moduleUnload(final byte[] name) { - sendCommand(MODULE, Keyword.UNLOAD.getRaw(), name); + sendCommand(MODULE, Keyword.UNLOAD.raw, name); } private ArrayList convertScoreMembersToByteArrays(final Map scoreMembers) { - ArrayList args = new ArrayList<>(scoreMembers.size() * 2); + ArrayList args = new ArrayList(scoreMembers.size() * 2); - for (Map.Entry entry : scoreMembers.entrySet()) { + for (Entry entry : scoreMembers.entrySet()) { args.add(toByteArray(entry.getValue())); args.add(entry.getKey()); } @@ -1583,69 +1181,9 @@ public class BinaryClient extends Connection { 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); + List args = new ArrayList(memberCoordinateMap.size() * 3); for (Entry entry : memberCoordinateMap.entrySet()) { GeoCoordinate coordinate = entry.getValue(); @@ -1661,350 +1199,7 @@ public class BinaryClient extends Connection { 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.raw; - 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 #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.raw; - args[index++] = groupname; - args[index++] = consumer; - System.arraycopy(bparams, 0, args, index, paramLength); - index += paramLength; - - args[index++] = Keyword.STREAMS.raw; - 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 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/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedis.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedis.java index 62a5ca09c..6297865c1 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedis.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedis.java @@ -14,118 +14,58 @@ 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 com.fr.third.redis.clients.jedis.args.*; -import com.fr.third.redis.clients.jedis.commands.AdvancedBinaryJedisCommands; -import com.fr.third.redis.clients.jedis.commands.BasicCommands; -import com.fr.third.redis.clients.jedis.commands.BinaryJedisCommands; -import com.fr.third.redis.clients.jedis.commands.BinaryScriptingCommands; -import com.fr.third.redis.clients.jedis.commands.MultiKeyBinaryCommands; -import com.fr.third.redis.clients.jedis.commands.ProtocolCommand; +import com.fr.third.redis.clients.jedis.commands.*; import com.fr.third.redis.clients.jedis.exceptions.InvalidURIException; import com.fr.third.redis.clients.jedis.exceptions.JedisDataException; import com.fr.third.redis.clients.jedis.exceptions.JedisException; -import com.fr.third.redis.clients.jedis.params.*; -import com.fr.third.redis.clients.jedis.resps.*; +import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; +import com.fr.third.redis.clients.jedis.params.SetParams; +import com.fr.third.redis.clients.jedis.params.ZAddParams; +import com.fr.third.redis.clients.jedis.params.ZIncrByParams; +import com.fr.third.redis.clients.jedis.util.JedisByteHashMap; import com.fr.third.redis.clients.jedis.util.JedisURIHelper; public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKeyBinaryCommands, AdvancedBinaryJedisCommands, BinaryScriptingCommands, Closeable { - - protected final Client client; + protected Client client = null; 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); + public BinaryJedis(final String host) { + URI uri = URI.create(host); if (JedisURIHelper.isValid(uri)) { - client = createClientFromURI(uri); - initializeFromURI(uri); + initializeClientFromURI(uri); } else { - client = new Client(uriString); + client = new Client(host); } } public BinaryJedis(final HostAndPort hp) { - this(hp, DefaultJedisClientConfig.builder().build()); + this(hp.getHost(), hp.getPort()); } 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(com.fr.third.redis.clients.jedis.util.SafeEncoder.encode(clientName)); - } - } catch (JedisException je) { - try { - if (isConnected()) { - quit(); - } - disconnect(); - } catch (Exception e) { - // - } - throw je; - } - } - public BinaryJedis(final String host, final int port, final boolean ssl) { - this(host, port, DefaultJedisClientConfig.builder().ssl(ssl).build()); + client = new Client(host, port, ssl); } 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()); + client = new Client(host, port, ssl, sslSocketFactory, sslParameters, hostnameVerifier); } public BinaryJedis(final String host, final int port, final int timeout) { @@ -144,63 +84,43 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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()); + client = new Client(host, port); + client.setConnectionTimeout(connectionTimeout); + client.setSoTimeout(soTimeout); } 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()); + client = new Client(host, port, ssl); + client.setConnectionTimeout(connectionTimeout); + client.setSoTimeout(soTimeout); } 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()); + client = new Client(host, port, ssl, sslSocketFactory, sslParameters, hostnameVerifier); + client.setConnectionTimeout(connectionTimeout); + client.setSoTimeout(soTimeout); } 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()); + client = new Client(shardInfo.getHost(), shardInfo.getPort(), shardInfo.getSsl(), + shardInfo.getSslSocketFactory(), shardInfo.getSslParameters(), + shardInfo.getHostnameVerifier()); + client.setConnectionTimeout(shardInfo.getConnectionTimeout()); + client.setSoTimeout(shardInfo.getSoTimeout()); + client.setPassword(shardInfo.getPassword()); + client.setDb(shardInfo.getDb()); } public BinaryJedis(URI uri) { - client = createClientFromURI(uri); - initializeFromURI(uri); + initializeClientFromURI(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()); + initializeClientFromURI(uri, sslSocketFactory, sslParameters, hostnameVerifier); } public BinaryJedis(final URI uri, final int timeout) { @@ -213,167 +133,47 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } public BinaryJedis(final URI uri, final int connectionTimeout, final int soTimeout) { - this(uri, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) - .socketTimeoutMillis(soTimeout).build()); + initializeClientFromURI(uri); + client.setConnectionTimeout(connectionTimeout); + client.setSoTimeout(soTimeout); } public BinaryJedis(final URI uri, final int connectionTimeout, final int soTimeout, - final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final SSLSocketFactory sslSocketFactory,final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - this(uri, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) - .socketTimeoutMillis(soTimeout).sslSocketFactory(sslSocketFactory) - .sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build()); + initializeClientFromURI(uri, sslSocketFactory, sslParameters, hostnameVerifier); + client.setConnectionTimeout(connectionTimeout); + client.setSoTimeout(soTimeout); } - 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()); + private void initializeClientFromURI(URI uri) { + initializeClientFromURI(uri, null, null, null); } - 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) { + private void initializeClientFromURI(URI uri, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { if (!JedisURIHelper.isValid(uri)) { throw new InvalidURIException(String.format( - "Cannot open Redis connection due invalid URI \"%s\".", uri.toString())); + "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) { + client = new Client(uri.getHost(), uri.getPort(), JedisURIHelper.isRedisSSLScheme(uri), + sslSocketFactory, sslParameters, hostnameVerifier); + String password = JedisURIHelper.getPassword(uri); if (password != null) { - String user = JedisURIHelper.getUser(uri); - if (user != null) { - auth(user, password); - } else { - auth(password); - } + client.auth(password); + client.getStatusCodeReply(); } + int dbIndex = JedisURIHelper.getDBIndex(uri); if (dbIndex > 0) { - select(dbIndex); - } - } - - /** - * @deprecated This constructor will be removed in future major release. - * - * Use {@link BinaryJedis#BinaryJedis(com.fr.third.redis.clients.jedis.JedisSocketFactory, com.fr.third.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(); + client.select(dbIndex); + client.getStatusCodeReply(); + client.setDb(dbIndex); } - - 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 - * @return - */ - @Override - public Boolean copy(byte[] srcKey, byte[] dstKey, int db, boolean replace) { - checkIsInMultiOrPipeline(); - client.copy(srcKey, dstKey, db, replace); - return BuilderFactory.BOOLEAN.build(client.getIntegerReply()); - } - - /** - * COPY source destination [DB destination-db] [REPLACE] - * - * @param srcKey the source key. - * @param dstKey the destination key. - * @param replace - * @return - */ - @Override - public Boolean copy(byte[] srcKey, byte[] dstKey, boolean replace) { - checkIsInMultiOrPipeline(); - client.copy(srcKey, dstKey, replace); - return BuilderFactory.BOOLEAN.build(client.getIntegerReply()); } - /** - * @return PONG - */ @Override public String ping() { checkIsInMultiOrPipeline(); @@ -382,7 +182,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } /** - * Works same as {@link #ping()} but returns argument message instead of PONG. + * Works same as ping() but returns argument message instead of PONG. * @param message * @return message */ @@ -439,29 +239,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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. */ @@ -489,8 +266,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } /** - * 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 + * Test if the specified key exists. The command returns "1" if the key exists, otherwise "0" is + * returned. Note that even keys set with an empty string as value will return "1". Time * complexity: O(1) * @param key * @return Boolean reply, true if the key exists, otherwise false @@ -577,18 +354,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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 @@ -628,7 +393,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * 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 + * @return Singe line reply, specifically the randomly selected key or an empty string is the * database is empty */ @Override @@ -645,7 +410,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * Time complexity: O(1) * @param oldkey * @param newkey - * @return Status code reply + * @return Status code repy */ @Override public String rename(final byte[] oldkey, final byte[] newkey) { @@ -684,7 +449,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * 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 + * Voltile 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. @@ -702,16 +467,16 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * 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) { + public Long expire(final byte[] key, final int 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 + * EXPIREAT works exctly 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 + * of specifing 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 @@ -826,19 +591,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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 @@ -857,7 +609,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } /** - * Get the values of all the specified keys. If one or more keys don't exist or is not of type + * Get the values of all the specified keys. If one or more keys dont 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. *

      @@ -900,7 +652,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * @return Status code reply */ @Override - public String setex(final byte[] key, final long seconds, final byte[] value) { + public String setex(final byte[] key, final int seconds, final byte[] value) { checkIsInMultiOrPipeline(); client.setex(key, seconds, value); return client.getStatusCodeReply(); @@ -1050,7 +802,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey public Double incrByFloat(final byte[] key, final double increment) { checkIsInMultiOrPipeline(); client.incrByFloat(key, increment); - return BuilderFactory.DOUBLE.build(client.getOne()); + String dval = client.getBulkReply(); + return (dval != null ? new Double(dval) : null); } /** @@ -1255,14 +1008,15 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey public Double hincrByFloat(final byte[] key, final byte[] field, final double value) { checkIsInMultiOrPipeline(); client.hincrByFloat(key, field, value); - return BuilderFactory.DOUBLE.build(client.getOne()); + final String dval = client.getBulkReply(); + return (dval != null ? new Double(dval) : null); } /** * 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 + * @return Return 1 if the hash stored at key contains the specified field. Return 0 if the key is * not found or the field is not present. */ @Override @@ -1342,49 +1096,14 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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(); - } + final List flatHash = client.getBinaryMultiBulkReply(); + final Map hash = new JedisByteHashMap(); + final Iterator iterator = flatHash.iterator(); + while (iterator.hasNext()) { + hash.put(iterator.next(), iterator.next()); + } - /** - * 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()); + return hash; } /** @@ -1570,7 +1289,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * 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 + * as value to remove against the list (a,b,c,hello,x,hello,hello) will have 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. @@ -1605,78 +1324,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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 @@ -1694,13 +1341,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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 @@ -1709,7 +1349,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey *

      * 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. + * from the list and pusing it as first element of the list, so it's a "list rotation" command. *

      * Time complexity: O(1) * @param srckey @@ -1795,9 +1435,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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); + return SetFromList.of(client.getBinaryMultiBulkReply()); } /** @@ -1841,12 +1479,12 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } /** - * Return true if member is a member of the set stored at key, otherwise false is returned. + * Return 1 if member is a member of the set stored at key, otherwise 0 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 + * @return Integer reply, specifically: 1 if the element is a member of the set 0 if the element * is not a member of the set OR if the key does not exist */ @Override @@ -1856,21 +1494,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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 @@ -1894,8 +1517,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } /** - * This commanad works exactly like {@link #sinter(byte[]...) SINTER} but instead of being returned - * the resulting set is stored as dstkey. + * This commnad works exactly like {@link #sinter(byte[]...) SINTER} but instead of being returned + * the resulting set is sotred as dstkey. *

      * Time complexity O(N*M) worst case where N is the cardinality of the smallest set and M the * number of sets @@ -1949,14 +1572,14 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * 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: @@ -2012,10 +1635,10 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } /** - * Add the specified member having the specified score to the sorted set stored at key. If member + * Add the specified member having the specifeid 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 + * member as sole member is crated. 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. @@ -2035,8 +1658,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } @Override - public Long zadd(final byte[] key, final double score, final byte[] member, - final ZAddParams params) { + 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(); @@ -2056,13 +1678,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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(); @@ -2093,7 +1708,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * 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. + * member is crated. 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. @@ -2114,8 +1729,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } @Override - public Double zincrby(final byte[] key, final double increment, final byte[] member, - final ZIncrByParams params) { + 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()); @@ -2188,27 +1802,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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. @@ -2238,84 +1831,73 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey public Double zscore(final byte[] key, final byte[] member) { checkIsInMultiOrPipeline(); client.zscore(key, member); - return BuilderFactory.DOUBLE.build(client.getOne()); + final String score = client.getBulkReply(); + return (score != null ? new Double(score) : null); } - /** - * 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()); + public Transaction multi() { + client.multi(); + client.getOne(); // expected OK + transaction = new Transaction(client); + return transaction; } - @Override - public Tuple zpopmax(final byte[] key) { - checkIsInMultiOrPipeline(); - client.zpopmax(key); - return BuilderFactory.TUPLE.build(client.getBinaryMultiBulkReply()); + protected void checkIsInMultiOrPipeline() { + if (client.isInMulti()) { + throw new JedisDataException( + "Cannot use Jedis when in Multi. Please use Transaction or reset jedis state."); + } else if (pipeline != null && pipeline.hasPipelinedResponse()) { + throw new JedisDataException( + "Cannot use Jedis when in Pipeline. Please use Pipeline or reset jedis state ."); + } } - @Override - public Set zpopmax(final byte[] key, final int count) { - checkIsInMultiOrPipeline(); - client.zpopmax(key, count); - return getTupledSet(); + public void connect() { + client.connect(); } - @Override - public Tuple zpopmin(final byte[] key) { - checkIsInMultiOrPipeline(); - client.zpopmin(key); - return BuilderFactory.TUPLE.build(client.getBinaryMultiBulkReply()); + public void disconnect() { + client.disconnect(); } - @Override - public Set zpopmin(final byte[] key, final int count) { - checkIsInMultiOrPipeline(); - client.zpopmin(key, count); - return getTupledSet(); - } + public void resetState() { + if (client.isConnected()) { + if (transaction != null) { + transaction.clear(); + } - public Transaction multi() { - client.multi(); - client.getOne(); // expected OK - transaction = new Transaction(client); - return transaction; - } + if (pipeline != null) { + pipeline.clear(); + } - protected void checkIsInMultiOrPipeline() { - if (client.isInMulti()) { - throw new JedisDataException( - "Cannot use Jedis when in Multi. Please use Transaction or reset jedis state."); - } else if (pipeline != null && pipeline.hasPipelinedResponse()) { - throw new JedisDataException( - "Cannot use Jedis when in Pipeline. Please use Pipeline or reset jedis state ."); + if (client.isInWatch()) { + unwatch(); + } + + client.resetState(); } + + transaction = null; + pipeline = null; } @Override public String watch(final byte[]... keys) { - checkIsInMultiOrPipeline(); client.watch(keys); return client.getStatusCodeReply(); } @Override public String unwatch() { - checkIsInMultiOrPipeline(); client.unwatch(); return client.getStatusCodeReply(); } + @Override + public void close() { + client.close(); + } + /** * Sort a Set or a List. *

      @@ -2342,65 +1924,65 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * 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]
          * 
      @@ -2417,79 +1999,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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 - * @return - */ - @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 - * @return - */ - @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 @@ -2554,12 +2063,54 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey */ @Override public List blpop(final int timeout, final byte[]... keys) { - return blpop(getKeysAndTimeout(timeout, keys)); + return blpop(getArgsAddTimeout(timeout, keys)); + } + + private byte[][] getArgsAddTimeout(int timeout, byte[][] keys) { + int size = keys.length; + final byte[][] args = new byte[size + 1][]; + for (int at = 0; at != size; ++at) { + args[at] = keys[at]; + } + args[size] = Protocol.toByteArray(timeout); + return args; + } + + /** + * 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 List blpop(final double timeout, final byte[]... keys) { - return blpop(getKeysAndTimeout(timeout, keys)); + public Long sort(final byte[] key, final byte[] dstkey) { + checkIsInMultiOrPipeline(); + client.sort(key, dstkey); + return client.getIntegerReply(); } /** @@ -2626,12 +2177,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey */ @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)); + return brpop(getArgsAddTimeout(timeout, keys)); } @Override @@ -2658,46 +2204,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } } - 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 @@ -2717,21 +2223,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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 - */ - @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); @@ -2752,27 +2243,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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). @@ -2879,8 +2349,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * @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 @@ -3005,8 +2473,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * @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 @@ -3027,14 +2493,10 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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); + 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()))); @@ -3111,10 +2573,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey *

      * 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 byte[] key, final long start, final long stop) { @@ -3150,34 +2608,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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 - * @return - */ - @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 - * @return - */ - @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 @@ -3251,34 +2681,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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 - * @return - */ - @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 - * @return - */ - @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 @@ -3382,8 +2784,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } @Override - public Set zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min, - final int offset, final int count) { + 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()); @@ -3494,7 +2895,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * Format of the returned String: *

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

          * edis_version:0.07
          * connected_clients:1
      @@ -3507,7 +2908,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
          * 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 @@ -3551,12 +2952,12 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * 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 + * server is arleady acting as slave, the command SLAVEOF NO ONE will turn off the replicaiton * 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 + * against the old server and start the synchrnonization 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 @@ -3589,7 +2990,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * are reported as a list of key-value pairs. *

      * Example: - * + * *

          * $ redis-cli config get '*'
          * 1. "dbfilename"
      @@ -3604,7 +3005,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
          * 10. "everysec"
          * 11. "save"
          * 12. "3600 1 300 100 60 10000"
      -   *
      +   * 
          * $ redis-cli config get 'm*'
          * 1. "masterauth"
          * 2. (nil)
      @@ -3635,24 +3036,18 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
         /**
          * 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.
      -   * 

      + * 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.
      • + *
      • 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.
      • + * 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. @@ -3681,12 +3076,12 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * 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. + *
      • The save paramter 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. *
      @@ -3701,6 +3096,10 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey return client.getBinaryBulkReply(); } + public boolean isConnected() { + return client.isConnected(); + } + @Override public Long strlen(final byte[] key) { checkIsInMultiOrPipeline(); @@ -3708,10 +3107,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey return client.getIntegerReply(); } - /** - * @deprecated This will be removed in next major release. - */ - @Deprecated public void sync() { client.sync(); } @@ -3733,7 +3128,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey */ @Override public Long persist(final byte[] key) { - checkIsInMultiOrPipeline(); client.persist(key); return client.getIntegerReply(); } @@ -3779,7 +3173,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey */ @Override public byte[] brpoplpush(final byte[] source, final byte[] destination, final int timeout) { - checkIsInMultiOrPipeline(); client.brpoplpush(source, destination, timeout); client.setTimeoutInfinite(); try { @@ -3874,12 +3267,14 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } } + @Override + public int getDB() { + return client.getDB(); + } + /** * 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 @@ -3903,10 +3298,9 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey @Override public Object eval(final byte[] script, final byte[] keyCount, final byte[]... params) { - checkIsInMultiOrPipeline(); - client.eval(script, keyCount, params); client.setTimeoutInfinite(); try { + client.eval(script, keyCount, params); return client.getOne(); } finally { client.rollbackTimeout(); @@ -3935,10 +3329,9 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey @Override public Object evalsha(final byte[] sha1, final int keyCount, final byte[]... params) { - checkIsInMultiOrPipeline(); - client.evalsha(sha1, keyCount, params); client.setTimeoutInfinite(); try { + client.evalsha(sha1, keyCount, params); return client.getOne(); } finally { client.rollbackTimeout(); @@ -3951,12 +3344,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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; @@ -3994,15 +3381,15 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } @Override - public List slowlogGetBinary() { + public List slowlogGetBinary() { client.slowlogGet(); - return client.getObjectMultiBulkReply(); + return client.getBinaryMultiBulkReply(); } @Override - public List slowlogGetBinary(final long entries) { + public List slowlogGetBinary(final long entries) { client.slowlogGet(entries); - return client.getObjectMultiBulkReply(); + return client.getBinaryMultiBulkReply(); } @Override @@ -4023,18 +3410,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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(); @@ -4064,34 +3439,19 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } @Override - public String restore(final byte[] key, final long ttl, final byte[] serializedValue) { + public String restore(final byte[] key, final int 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 + * Voltile 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 @@ -4099,7 +3459,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * {@link #persist(byte[]) PERSIST} command. *

      * Time complexity: O(1) - * @see PEXPIRE Command + * @see PEXPIRE Command * @param key * @param milliseconds * @return Integer reply, specifically: 1: the timeout was set. 0: the timeout was not set since @@ -4135,244 +3495,49 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * @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 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) { + public String clientKill(final byte[] client) { checkIsInMultiOrPipeline(); - this.client.clientKill(ip, port); + this.client.clientKill(client); return this.client.getStatusCodeReply(); } - @Override - public Long clientKill(ClientKillParams params) { - checkIsInMultiOrPipeline(); - this.client.clientKill(params); - return this.client.getIntegerReply(); - } - - @Override - public byte[] clientGetnameBinary() { + public String clientGetname() { checkIsInMultiOrPipeline(); client.clientGetname(); - return client.getBinaryBulkReply(); + return client.getBulkReply(); } - @Override - public byte[] clientListBinary() { + public String clientList() { checkIsInMultiOrPipeline(); client.clientList(); - 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(); + return client.getBulkReply(); } - @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 - * @return - */ - @Override - public Long clientUnblock(final long clientId, final UnblockType unblockType) { - checkIsInMultiOrPipeline(); - client.clientUnblock(clientId, unblockType); - return client.getIntegerReply(); - } - - public String clientPause(final long timeout) { - checkIsInMultiOrPipeline(); - client.clientPause(timeout); - 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, + public String migrate(final byte[] 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(); - } - /** * Syncrhonous replication of Redis as described here: http://antirez.com/news/66 Since Java * Object class has implemented "wait" method, we cannot use it, so I had to change the name of @@ -4423,7 +3588,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey List result = client.getObjectMultiBulkReply(); byte[] newcursor = (byte[]) result.get(0); List rawResults = (List) result.get(1); - return new ScanResult<>(newcursor, rawResults); + return new ScanResult(newcursor, rawResults); } @Override @@ -4438,13 +3603,13 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey client.hscan(key, cursor, params); List result = client.getObjectMultiBulkReply(); byte[] newcursor = (byte[]) result.get(0); - List> results = new ArrayList<>(); + 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())); + results.add(new AbstractMap.SimpleEntry(iterator.next(), iterator.next())); } - return new ScanResult<>(newcursor, results); + return new ScanResult>(newcursor, results); } @Override @@ -4459,7 +3624,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey List result = client.getObjectMultiBulkReply(); byte[] newcursor = (byte[]) result.get(0); List rawResults = (List) result.get(1); - return new ScanResult<>(newcursor, rawResults); + return new ScanResult(newcursor, rawResults); } @Override @@ -4473,18 +3638,17 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey client.zscan(key, cursor, params); List result = client.getObjectMultiBulkReply(); byte[] newcursor = (byte[]) result.get(0); - List results = new ArrayList<>(); + 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 new ScanResult(newcursor, results); } @Override - public Long geoadd(final byte[] key, final double longitude, final double latitude, - final byte[] member) { + 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(); @@ -4497,26 +3661,20 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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()); + String dval = client.getBulkReply(); + return (dval != null ? new Double(dval) : null); } @Override - public Double geodist(final byte[] key, final byte[] member1, final byte[] member2, - final GeoUnit unit) { + 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()); + String dval = client.getBulkReply(); + return (dval != null ? new Double(dval) : null); } @Override @@ -4534,86 +3692,37 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } @Override - public List georadius(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { + 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) { + 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) { + 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) { + 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 @@ -4623,7 +3732,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey */ protected static class SetFromList extends AbstractSet implements Serializable { private static final long serialVersionUID = -2850347066962734052L; - private final List list; + private final transient List list; private SetFromList(List list) { if (list == null) { @@ -4689,9 +3798,13 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey @Override public boolean equals(Object o) { - if (o == null) return false; - if (o == this) return true; - if (!(o instanceof Set)) return false; + if (o == this) { + return true; + } + + if (!(o instanceof Set)) { + return false; + } Collection c = (Collection) o; if (c.size() != size()) { @@ -4717,7 +3830,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } protected static SetFromList of(List list) { - return new SetFromList<>(list); + return new SetFromList(list); } } @@ -4728,292 +3841,10 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey 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 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/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedisCluster.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedisCluster.java index be61197b3..910044e94 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedisCluster.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedisCluster.java @@ -1,183 +1,67 @@ package com.fr.third.redis.clients.jedis; -import com.fr.third.redis.clients.jedis.args.*; import com.fr.third.redis.clients.jedis.commands.BinaryJedisClusterCommands; import com.fr.third.redis.clients.jedis.commands.JedisClusterBinaryScriptingCommands; import com.fr.third.redis.clients.jedis.commands.MultiKeyBinaryJedisClusterCommands; -import com.fr.third.redis.clients.jedis.commands.ProtocolCommand; -import com.fr.third.redis.clients.jedis.params.*; -import com.fr.third.redis.clients.jedis.resps.*; -import com.fr.third.redis.clients.jedis.util.JedisClusterHashTagUtil; +import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; +import com.fr.third.redis.clients.jedis.params.SetParams; +import com.fr.third.redis.clients.jedis.params.ZAddParams; +import com.fr.third.redis.clients.jedis.params.ZIncrByParams; import com.fr.third.redis.clients.jedis.util.KeyMergeUtil; import com.fr.third.redis.clients.jedis.util.SafeEncoder; import java.io.Closeable; -import java.time.Duration; +import java.util.Collection; 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 com.fr.third.org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import com.fr.third.redis.clients.jedis.util.JedisClusterHashTagUtil; 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 static final int DEFAULT_TIMEOUT = 2000; + protected static final int DEFAULT_MAX_ATTEMPTS = 5; protected int maxAttempts; - /** - * After this amount of time we will do no more retries and report the operation as failed. - * - * Defaults to {@link #DEFAULT_TIMEOUT} if unset, or {@code soTimeout} if available. - */ - 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); + this(nodes, timeout, DEFAULT_MAX_ATTEMPTS, new GenericObjectPoolConfig()); } - 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 nodes) { + this(nodes, DEFAULT_TIMEOUT); } - public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, - int soTimeout, int maxAttempts, String user, String password, String clientName, - GenericObjectPoolConfig poolConfig) { + public BinaryJedisCluster(Set jedisClusterNode, int timeout, int maxAttempts, + final GenericObjectPoolConfig poolConfig) { this.connectionHandler = new JedisSlotBasedConnectionHandler(jedisClusterNode, poolConfig, - connectionTimeout, soTimeout, user, password, clientName); + timeout); this.maxAttempts = maxAttempts; - this.maxTotalRetriesDuration = Duration.ofMillis(soTimeout); } public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, - int soTimeout, int infiniteSoTimeout, int maxAttempts, String user, String password, - String clientName, GenericObjectPoolConfig poolConfig) { + int soTimeout, int maxAttempts, final GenericObjectPoolConfig poolConfig) { this.connectionHandler = new JedisSlotBasedConnectionHandler(jedisClusterNode, poolConfig, - connectionTimeout, soTimeout, infiniteSoTimeout, user, password, clientName); + connectionTimeout, soTimeout); this.maxAttempts = maxAttempts; - this.maxTotalRetriesDuration = Duration.ofMillis(soTimeout); - } - - public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, - int soTimeout, int maxAttempts, String password, String clientName, - GenericObjectPoolConfig poolConfig, boolean ssl) { - this(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, clientName, - poolConfig, ssl, null, null, null, null); - } - - public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, - int soTimeout, int maxAttempts, String user, String password, String clientName, - GenericObjectPoolConfig poolConfig, boolean ssl) { - this(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, user, password, clientName, - poolConfig, ssl, null, null, null, null); } - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, - int soTimeout, int maxAttempts, String password, String clientName, - GenericObjectPoolConfig poolConfig, boolean ssl, SSLSocketFactory sslSocketFactory, - SSLParameters sslParameters, HostnameVerifier hostnameVerifier, - JedisClusterHostAndPortMap hostAndPortMap) { - this(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, null, password, clientName, - poolConfig, ssl, sslSocketFactory, sslParameters, hostnameVerifier, hostAndPortMap); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, - int soTimeout, int maxAttempts, String user, String password, String clientName, - GenericObjectPoolConfig poolConfig, boolean ssl, SSLSocketFactory sslSocketFactory, - SSLParameters sslParameters, HostnameVerifier hostnameVerifier, - JedisClusterHostAndPortMap hostAndPortMap) { - this(jedisClusterNode, connectionTimeout, soTimeout, 0, maxAttempts, user, password, - clientName, poolConfig, ssl, sslSocketFactory, sslParameters, hostnameVerifier, - hostAndPortMap); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, - int soTimeout, int infiniteSoTimeout, int maxAttempts, String user, String password, - String clientName, GenericObjectPoolConfig poolConfig, boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier, JedisClusterHostAndPortMap hostAndPortMap) { - this(jedisClusterNode, connectionTimeout, soTimeout, infiniteSoTimeout, maxAttempts, user, - password, clientName, poolConfig, ssl, sslSocketFactory, sslParameters, hostnameVerifier, - hostAndPortMap, Duration.ofMillis((long) soTimeout * maxAttempts)); - } - - /** - * @param maxTotalRetriesDuration After this amount of time we will do no more retries and report - * the operation as failed. - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout, - int infiniteSoTimeout, int maxAttempts, String user, String password, String clientName, - GenericObjectPoolConfig poolConfig, boolean ssl, SSLSocketFactory sslSocketFactory, - SSLParameters sslParameters, HostnameVerifier hostnameVerifier, - JedisClusterHostAndPortMap hostAndPortMap, Duration maxTotalRetriesDuration) { + public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout, int maxAttempts, String password, GenericObjectPoolConfig poolConfig) { this.connectionHandler = new JedisSlotBasedConnectionHandler(jedisClusterNode, poolConfig, - connectionTimeout, soTimeout, infiniteSoTimeout, user, password, clientName, ssl, - sslSocketFactory, sslParameters, hostnameVerifier, hostAndPortMap); + connectionTimeout, soTimeout, password); this.maxAttempts = maxAttempts; - this.maxTotalRetriesDuration = maxTotalRetriesDuration; - } - - public BinaryJedisCluster(Set jedisClusterNode, JedisClientConfig clientConfig, - int maxAttempts, GenericObjectPoolConfig poolConfig) { - this(jedisClusterNode, clientConfig, maxAttempts, - Duration.ofMillis((long) DEFAULT_TIMEOUT * maxAttempts), poolConfig); } - public BinaryJedisCluster(Set jedisClusterNode, JedisClientConfig clientConfig, - int maxAttempts, Duration maxTotalRetriesDuration, GenericObjectPoolConfig poolConfig) { + public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout, int maxAttempts, String password, String clientName, GenericObjectPoolConfig poolConfig) { this.connectionHandler = new JedisSlotBasedConnectionHandler(jedisClusterNode, poolConfig, - clientConfig); + connectionTimeout, soTimeout, password, clientName); this.maxAttempts = maxAttempts; - this.maxTotalRetriesDuration = maxTotalRetriesDuration; } @Override @@ -192,22 +76,12 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, } 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); + return this.connectionHandler.getConnectionFromSlot(slot); } @Override public String set(final byte[] key, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.set(key, value); @@ -217,7 +91,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public String set(final byte[] key, final byte[] value, final SetParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.set(key, value, params); @@ -227,7 +101,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public byte[] get(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public byte[] execute(Jedis connection) { return connection.get(key); @@ -235,29 +109,9 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.exists(keys); @@ -267,7 +121,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Boolean exists(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.exists(key); @@ -277,7 +131,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long persist(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.persist(key); @@ -287,7 +141,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public String type(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.type(key); @@ -297,7 +151,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public byte[] dump(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public byte[] execute(Jedis connection) { return connection.dump(key); @@ -306,8 +160,8 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, } @Override - public String restore(final byte[] key, final long ttl, final byte[] serializedValue) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + public String restore(final byte[] key, final int ttl, final byte[] serializedValue) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.restore(key, ttl, serializedValue); @@ -315,20 +169,9 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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 int seconds) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.expire(key, seconds); @@ -338,7 +181,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long pexpire(final byte[] key, final long milliseconds) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pexpire(key, milliseconds); @@ -348,7 +191,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long expireAt(final byte[] key, final long unixTime) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.expireAt(key, unixTime); @@ -358,7 +201,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long pexpireAt(final byte[] key, final long millisecondsTimestamp) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pexpireAt(key, millisecondsTimestamp); @@ -368,7 +211,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long ttl(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.ttl(key); @@ -378,7 +221,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long pttl(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pttl(key); @@ -388,7 +231,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long touch(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.touch(key); @@ -398,7 +241,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long touch(final byte[]... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.touch(keys); @@ -408,7 +251,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Boolean setbit(final byte[] key, final long offset, final boolean value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.setbit(key, offset, value); @@ -418,7 +261,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Boolean setbit(final byte[] key, final long offset, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.setbit(key, offset, value); @@ -428,7 +271,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Boolean getbit(final byte[] key, final long offset) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.getbit(key, offset); @@ -438,7 +281,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long setrange(final byte[] key, final long offset, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.setrange(key, offset, value); @@ -448,7 +291,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public byte[] getrange(final byte[] key, final long startOffset, final long endOffset) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public byte[] execute(Jedis connection) { return connection.getrange(key, startOffset, endOffset); @@ -458,7 +301,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public byte[] getSet(final byte[] key, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public byte[] execute(Jedis connection) { return connection.getSet(key, value); @@ -468,7 +311,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long setnx(final byte[] key, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.setnx(key, value); @@ -478,7 +321,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public String psetex(final byte[] key, final long milliseconds, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.psetex(key, milliseconds, value); @@ -487,8 +330,8 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, } @Override - public String setex(final byte[] key, final long seconds, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + public String setex(final byte[] key, final int seconds, final byte[] value) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.setex(key, seconds, value); @@ -498,7 +341,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long decrBy(final byte[] key, final long decrement) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.decrBy(key, decrement); @@ -508,7 +351,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long decr(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.decr(key); @@ -518,7 +361,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long incrBy(final byte[] key, final long increment) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.incrBy(key, increment); @@ -528,7 +371,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Double incrByFloat(final byte[] key, final double increment) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.incrByFloat(key, increment); @@ -538,7 +381,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long incr(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.incr(key); @@ -548,7 +391,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long append(final byte[] key, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.append(key, value); @@ -558,7 +401,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public byte[] substr(final byte[] key, final int start, final int end) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public byte[] execute(Jedis connection) { return connection.substr(key, start, end); @@ -568,7 +411,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long hset(final byte[] key, final byte[] field, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hset(key, field, value); @@ -578,7 +421,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long hset(final byte[] key, final Map hash) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hset(key, hash); @@ -588,7 +431,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public byte[] hget(final byte[] key, final byte[] field) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public byte[] execute(Jedis connection) { return connection.hget(key, field); @@ -598,7 +441,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long hsetnx(final byte[] key, final byte[] field, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hsetnx(key, field, value); @@ -608,7 +451,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public String hmset(final byte[] key, final Map hash) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.hmset(key, hash); @@ -618,7 +461,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public List hmget(final byte[] key, final byte[]... fields) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.hmget(key, fields); @@ -628,7 +471,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long hincrBy(final byte[] key, final byte[] field, final long value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hincrBy(key, field, value); @@ -638,7 +481,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Double hincrByFloat(final byte[] key, final byte[] field, final double value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.hincrByFloat(key, field, value); @@ -648,7 +491,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Boolean hexists(final byte[] key, final byte[] field) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.hexists(key, field); @@ -658,7 +501,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long hdel(final byte[] key, final byte[]... field) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hdel(key, field); @@ -668,7 +511,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long hlen(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.hlen(key); @@ -678,7 +521,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set hkeys(final byte[] key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.hkeys(key); @@ -687,10 +530,10 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, } @Override - public List hvals(final byte[] key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + public Collection hvals(final byte[] key) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override - public List execute(Jedis connection) { + public Collection execute(Jedis connection) { return connection.hvals(key); } }.runBinary(key); @@ -698,7 +541,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Map hgetAll(final byte[] key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Map execute(Jedis connection) { return connection.hgetAll(key); @@ -706,39 +549,9 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.rpush(key, args); @@ -748,7 +561,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long lpush(final byte[] key, final byte[]... args) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.lpush(key, args); @@ -758,7 +571,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long llen(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.llen(key); @@ -768,7 +581,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public List lrange(final byte[] key, final long start, final long stop) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.lrange(key, start, stop); @@ -778,7 +591,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public String ltrim(final byte[] key, final long start, final long stop) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.ltrim(key, start, stop); @@ -788,7 +601,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public byte[] lindex(final byte[] key, final long index) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public byte[] execute(Jedis connection) { return connection.lindex(key, index); @@ -798,7 +611,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public String lset(final byte[] key, final long index, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.lset(key, index, value); @@ -808,7 +621,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long lrem(final byte[] key, final long count, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.lrem(key, count, value); @@ -818,7 +631,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public byte[] lpop(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public byte[] execute(Jedis connection) { return connection.lpop(key); @@ -826,50 +639,9 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public byte[] execute(Jedis connection) { return connection.rpop(key); @@ -877,19 +649,9 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sadd(key, member); @@ -899,7 +661,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set smembers(final byte[] key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.smembers(key); @@ -909,7 +671,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long srem(final byte[] key, final byte[]... member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.srem(key, member); @@ -919,7 +681,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public byte[] spop(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public byte[] execute(Jedis connection) { return connection.spop(key); @@ -929,7 +691,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set spop(final byte[] key, final long count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.spop(key, count); @@ -939,7 +701,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long scard(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.scard(key); @@ -949,7 +711,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Boolean sismember(final byte[] key, final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Boolean execute(Jedis connection) { return connection.sismember(key, member); @@ -957,19 +719,9 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public byte[] execute(Jedis connection) { return connection.srandmember(key); @@ -979,7 +731,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long strlen(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.strlen(key); @@ -989,7 +741,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long zadd(final byte[] key, final double score, final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zadd(key, score, member); @@ -1000,7 +752,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long zadd(final byte[] key, final double score, final byte[] member, final ZAddParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zadd(key, score, member, params); @@ -1010,7 +762,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long zadd(final byte[] key, final Map scoreMembers) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zadd(key, scoreMembers); @@ -1020,7 +772,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long zadd(final byte[] key, final Map scoreMembers, final ZAddParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zadd(key, scoreMembers, params); @@ -1028,50 +780,9 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrange(key, start, stop); @@ -1081,7 +792,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long zrem(final byte[] key, final byte[]... members) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zrem(key, members); @@ -1091,7 +802,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Double zincrby(final byte[] key, final double increment, final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.zincrby(key, increment, member); @@ -1102,7 +813,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Double zincrby(final byte[] key, final double increment, final byte[] member, final ZIncrByParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.zincrby(key, increment, member, params); @@ -1112,7 +823,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long zrank(final byte[] key, final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zrank(key, member); @@ -1122,7 +833,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long zrevrank(final byte[] key, final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zrevrank(key, member); @@ -1132,7 +843,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set zrevrange(final byte[] key, final long start, final long stop) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrevrange(key, start, stop); @@ -1142,7 +853,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set zrangeWithScores(final byte[] key, final long start, final long stop) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrangeWithScores(key, start, stop); @@ -1152,7 +863,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set zrevrangeWithScores(final byte[] key, final long start, final long stop) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrevrangeWithScores(key, start, stop); @@ -1160,39 +871,9 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zcard(key); @@ -1202,7 +883,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Double zscore(final byte[] key, final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.zscore(key, member); @@ -1210,59 +891,9 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.sort(key); @@ -1272,7 +903,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public List sort(final byte[] key, final SortingParams sortingParameters) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.sort(key, sortingParameters); @@ -1282,7 +913,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long zcount(final byte[] key, final double min, final double max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zcount(key, min, max); @@ -1292,7 +923,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long zcount(final byte[] key, final byte[] min, final byte[] max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zcount(key, min, max); @@ -1302,7 +933,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set zrangeByScore(final byte[] key, final double min, final double max) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrangeByScore(key, min, max); @@ -1312,7 +943,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set zrangeByScore(final byte[] key, final byte[] min, final byte[] max) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrangeByScore(key, min, max); @@ -1322,7 +953,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set zrevrangeByScore(final byte[] key, final double max, final double min) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrevrangeByScore(key, max, min); @@ -1333,7 +964,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrangeByScore(key, min, max, offset, count); @@ -1343,7 +974,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrevrangeByScore(key, max, min); @@ -1354,7 +985,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrangeByScore(key, min, max, offset, count); @@ -1365,7 +996,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrevrangeByScore(key, max, min, offset, count); @@ -1375,7 +1006,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set zrangeByScoreWithScores(final byte[] key, final double min, final double max) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max); @@ -1385,7 +1016,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min); @@ -1396,7 +1027,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max, offset, count); @@ -1407,7 +1038,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrevrangeByScore(key, max, min, offset, count); @@ -1417,7 +1048,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max); @@ -1427,7 +1058,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set zrevrangeByScoreWithScores(final byte[] key, final byte[] max, final byte[] min) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min); @@ -1438,7 +1069,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrangeByScoreWithScores(key, min, max, offset, count); @@ -1449,7 +1080,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min, offset, count); @@ -1460,7 +1091,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrevrangeByScoreWithScores(key, max, min, offset, count); @@ -1470,7 +1101,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long zremrangeByRank(final byte[] key, final long start, final long stop) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zremrangeByRank(key, start, stop); @@ -1480,7 +1111,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long zremrangeByScore(final byte[] key, final double min, final double max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zremrangeByScore(key, min, max); @@ -1490,7 +1121,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long zremrangeByScore(final byte[] key, final byte[] min, final byte[] max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zremrangeByScore(key, min, max); @@ -1501,7 +1132,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long linsert(final byte[] key, final ListPosition where, final byte[] pivot, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.linsert(key, where, pivot, value); @@ -1511,7 +1142,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long lpushx(final byte[] key, final byte[]... arg) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.lpushx(key, arg); @@ -1521,7 +1152,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long rpushx(final byte[] key, final byte[]... arg) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.rpushx(key, arg); @@ -1531,7 +1162,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long del(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.del(key); @@ -1541,7 +1172,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long unlink(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.unlink(key); @@ -1551,7 +1182,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long unlink(final byte[]... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.unlink(keys); @@ -1562,7 +1193,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public byte[] echo(final byte[] arg) { // note that it'll be run from arbitary node - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public byte[] execute(Jedis connection) { return connection.echo(arg); @@ -1572,7 +1203,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long bitcount(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.bitcount(key); @@ -1582,7 +1213,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long bitcount(final byte[] key, final long start, final long end) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.bitcount(key, start, end); @@ -1592,7 +1223,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long pfadd(final byte[] key, final byte[]... elements) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pfadd(key, elements); @@ -1602,7 +1233,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public long pfcount(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pfcount(key); @@ -1612,7 +1243,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public List srandmember(final byte[] key, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.srandmember(key, count); @@ -1622,7 +1253,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long zlexcount(final byte[] key, final byte[] min, final byte[] max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zlexcount(key, min, max); @@ -1632,7 +1263,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set zrangeByLex(final byte[] key, final byte[] min, final byte[] max) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrangeByLex(key, min, max); @@ -1643,7 +1274,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrangeByLex(key, min, max, offset, count); @@ -1653,7 +1284,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrevrangeByLex(key, max, min); @@ -1664,7 +1295,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.zrevrangeByLex(key, max, min, offset, count); @@ -1674,7 +1305,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long zremrangeByLex(final byte[] key, final byte[] min, final byte[] max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zremrangeByLex(key, min, max); @@ -1684,7 +1315,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Object eval(final byte[] script, final byte[] keyCount, final byte[]... params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.eval(script, keyCount, params); @@ -1694,7 +1325,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Object eval(final byte[] script, final int keyCount, final byte[]... params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.eval(script, keyCount, params); @@ -1704,7 +1335,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Object eval(final byte[] script, final List keys, final List args) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.eval(script, keys, args); @@ -1714,7 +1345,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Object eval(final byte[] script, final byte[] sampleKey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.eval(script); @@ -1724,7 +1355,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Object evalsha(final byte[] sha1, final byte[] sampleKey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.evalsha(sha1); @@ -1734,7 +1365,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Object evalsha(final byte[] sha1, final List keys, final List args) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.evalsha(sha1, keys, args); @@ -1744,7 +1375,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Object evalsha(final byte[] sha1, final int keyCount, final byte[]... params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Object execute(Jedis connection) { return connection.evalsha(sha1, keyCount, params); @@ -1754,7 +1385,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public List scriptExists(final byte[] sampleKey, final byte[]... sha1) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.scriptExists(sha1); @@ -1764,7 +1395,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public byte[] scriptLoad(final byte[] script, final byte[] sampleKey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public byte[] execute(Jedis connection) { return connection.scriptLoad(script); @@ -1774,7 +1405,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public String scriptFlush(final byte[] sampleKey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.scriptFlush(); @@ -1782,19 +1413,9 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.scriptKill(); @@ -1804,7 +1425,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long del(final byte[]... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.del(keys); @@ -1812,41 +1433,9 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.blpop(timeout, keys); @@ -1856,17 +1445,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.brpop(timeout, keys); @@ -1874,29 +1453,9 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.mget(keys); @@ -1912,7 +1471,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, keys[keyIdx] = keysvalues[keyIdx * 2]; } - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.mset(keysvalues); @@ -1928,7 +1487,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, keys[keyIdx] = keysvalues[keyIdx * 2]; } - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.msetnx(keysvalues); @@ -1938,7 +1497,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public String rename(final byte[] oldkey, final byte[] newkey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.rename(oldkey, newkey); @@ -1948,7 +1507,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long renamenx(final byte[] oldkey, final byte[] newkey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.renamenx(oldkey, newkey); @@ -1958,7 +1517,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public byte[] rpoplpush(final byte[] srckey, final byte[] dstkey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public byte[] execute(Jedis connection) { return connection.rpoplpush(srckey, dstkey); @@ -1968,7 +1527,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set sdiff(final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.sdiff(keys); @@ -1980,7 +1539,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, public Long sdiffstore(final byte[] dstkey, final byte[]... keys) { byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, keys); - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sdiffstore(dstkey, keys); @@ -1990,7 +1549,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set sinter(final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.sinter(keys); @@ -2002,7 +1561,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, public Long sinterstore(final byte[] dstkey, final byte[]... keys) { byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, keys); - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sinterstore(dstkey, keys); @@ -2012,7 +1571,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long smove(final byte[] srckey, final byte[] dstkey, final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.smove(srckey, dstkey, member); @@ -2022,7 +1581,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long sort(final byte[] key, final SortingParams sortingParameters, final byte[] dstkey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sort(key, sortingParameters, dstkey); @@ -2032,7 +1591,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long sort(final byte[] key, final byte[] dstkey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sort(key, dstkey); @@ -2042,7 +1601,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Set sunion(final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.sunion(keys); @@ -2054,7 +1613,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, public Long sunionstore(final byte[] dstkey, final byte[]... keys) { byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, keys); - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.sunionstore(dstkey, keys); @@ -2062,31 +1621,11 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zinterstore(dstkey, sets); @@ -2098,7 +1637,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, public Long zinterstore(final byte[] dstkey, final ZParams params, final byte[]... sets) { byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, sets); - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zinterstore(dstkey, params, sets); @@ -2106,31 +1645,11 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zunionstore(dstkey, sets); @@ -2142,7 +1661,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, public Long zunionstore(final byte[] dstkey, final ZParams params, final byte[]... sets) { byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, sets); - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.zunionstore(dstkey, params, sets); @@ -2152,7 +1671,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public byte[] brpoplpush(final byte[] source, final byte[] destination, final int timeout) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public byte[] execute(Jedis connection) { return connection.brpoplpush(source, destination, timeout); @@ -2162,7 +1681,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long publish(final byte[] channel, final byte[] message) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.publish(channel, message); @@ -2172,7 +1691,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public void subscribe(final BinaryJedisPubSub jedisPubSub, final byte[]... channels) { - new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Integer execute(Jedis connection) { connection.subscribe(jedisPubSub, channels); @@ -2183,7 +1702,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public void psubscribe(final BinaryJedisPubSub jedisPubSub, final byte[]... patterns) { - new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Integer execute(Jedis connection) { connection.psubscribe(jedisPubSub, patterns); @@ -2196,7 +1715,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, public Long bitop(final BitOP op, final byte[] destKey, final byte[]... srcKeys) { byte[][] wholeKeys = KeyMergeUtil.merge(destKey, srcKeys); - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.bitop(op, destKey, srcKeys); @@ -2208,7 +1727,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, public String pfmerge(final byte[] destkey, final byte[]... sourcekeys) { byte[][] wholeKeys = KeyMergeUtil.merge(destkey, sourcekeys); - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public String execute(Jedis connection) { return connection.pfmerge(destkey, sourcekeys); @@ -2218,7 +1737,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long pfcount(final byte[]... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.pfcount(keys); @@ -2229,7 +1748,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long geoadd(final byte[] key, final double longitude, final double latitude, final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.geoadd(key, longitude, latitude, member); @@ -2239,7 +1758,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Long geoadd(final byte[] key, final Map memberCoordinateMap) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Long execute(Jedis connection) { return connection.geoadd(key, memberCoordinateMap); @@ -2247,19 +1766,9 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.geodist(key, member1, member2); @@ -2270,7 +1779,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public Double geodist(final byte[] key, final byte[] member1, final byte[] member2, final GeoUnit unit) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @Override public Double execute(Jedis connection) { return connection.geodist(key, member1, member2, unit); @@ -2280,7 +1789,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public List geohash(final byte[] key, final byte[]... members) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.geohash(key, members); @@ -2290,7 +1799,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public List geopos(final byte[] key, final byte[]... members) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.geopos(key, members); @@ -2301,7 +1810,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.georadius(key, longitude, latitude, radius, unit); @@ -2309,21 +1818,10 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.georadius(key, longitude, latitude, radius, unit, param); @@ -2331,34 +1829,10 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.georadiusByMember(key, member, radius, unit); @@ -2366,21 +1840,10 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.georadiusByMember(key, member, radius, unit, param); @@ -2388,29 +1851,6 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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 Set keys(final byte[] pattern) { if (pattern == null || pattern.length == 0) { @@ -2418,12 +1858,10 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, + " 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 )"); + 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) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public Set execute(Jedis connection) { return connection.keys(pattern); @@ -2442,25 +1880,22 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, } if (!JedisClusterHashTagUtil.isClusterCompliantMatchPattern(matchPattern)) { - throw new IllegalArgumentException( - BinaryJedisCluster.class.getSimpleName() - + " only supports SCAN commands with MATCH patterns containing hash-tags" - + " ( curly-brackets enclosed strings )"); + 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) { + return new JedisClusterCommand< ScanResult>(connectionHandler, maxAttempts) { @Override public ScanResult execute(Jedis connection) { return connection.scan(cursor, params); } }.runBinary(matchPattern); } - + @Override public ScanResult> hscan(final byte[] key, final byte[] cursor) { return new JedisClusterCommand>>(connectionHandler, - maxAttempts, maxTotalRetriesDuration) { + maxAttempts) { @Override public ScanResult> execute(Jedis connection) { return connection.hscan(key, cursor); @@ -2472,7 +1907,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, public ScanResult> hscan(final byte[] key, final byte[] cursor, final ScanParams params) { return new JedisClusterCommand>>(connectionHandler, - maxAttempts, maxTotalRetriesDuration) { + maxAttempts) { @Override public ScanResult> execute(Jedis connection) { return connection.hscan(key, cursor, params); @@ -2482,7 +1917,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public ScanResult sscan(final byte[] key, final byte[] cursor) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public ScanResult execute(Jedis connection) { return connection.sscan(key, cursor); @@ -2492,7 +1927,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public ScanResult sscan(final byte[] key, final byte[] cursor, final ScanParams params) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public ScanResult execute(Jedis connection) { return connection.sscan(key, cursor, params); @@ -2502,7 +1937,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public ScanResult zscan(final byte[] key, final byte[] cursor) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public ScanResult execute(Jedis connection) { return connection.zscan(key, cursor); @@ -2512,7 +1947,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public ScanResult zscan(final byte[] key, final byte[] cursor, final ScanParams params) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public ScanResult execute(Jedis connection) { return connection.zscan(key, cursor, params); @@ -2522,7 +1957,7 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, @Override public List bitfield(final byte[] key, final byte[]... arguments) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { @Override public List execute(Jedis connection) { return connection.bitfield(key, arguments); @@ -2530,357 +1965,13 @@ public class BinaryJedisCluster implements BinaryJedisClusterCommands, }.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) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { @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 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/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedisPubSub.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedisPubSub.java index 4aa8c4c76..8721f79a6 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedisPubSub.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedisPubSub.java @@ -2,7 +2,6 @@ package com.fr.third.redis.clients.jedis; import static com.fr.third.redis.clients.jedis.Protocol.Keyword.MESSAGE; import static com.fr.third.redis.clients.jedis.Protocol.Keyword.PMESSAGE; -import static com.fr.third.redis.clients.jedis.Protocol.Keyword.PONG; import static com.fr.third.redis.clients.jedis.Protocol.Keyword.PSUBSCRIBE; import static com.fr.third.redis.clients.jedis.Protocol.Keyword.PUNSUBSCRIBE; import static com.fr.third.redis.clients.jedis.Protocol.Keyword.SUBSCRIBE; @@ -35,9 +34,6 @@ public abstract class BinaryJedisPubSub { public void onPSubscribe(byte[] pattern, int subscribedChannels) { } - public void onPong(byte[] pattern) { - } - public void unsubscribe() { client.unsubscribe(); client.flush(); @@ -68,16 +64,6 @@ public abstract class BinaryJedisPubSub { client.flush(); } - public void ping() { - client.ping(); - client.flush(); - } - - public void ping(byte[] argument) { - client.ping(argument); - client.flush(); - } - public boolean isSubscribed() { return subscribedChannels > 0; } @@ -98,40 +84,37 @@ public abstract class BinaryJedisPubSub { private void process(Client client) { do { - List reply = client.getUnflushedObjectMultiBulkReply(); + List reply = client.getRawObjectMultiBulkReply(); final Object firstObj = reply.get(0); if (!(firstObj instanceof byte[])) { throw new JedisException("Unknown message type: " + firstObj); } final byte[] resp = (byte[]) firstObj; - if (Arrays.equals(SUBSCRIBE.getRaw(), resp)) { + if (Arrays.equals(SUBSCRIBE.raw, resp)) { subscribedChannels = ((Long) reply.get(2)).intValue(); final byte[] bchannel = (byte[]) reply.get(1); onSubscribe(bchannel, subscribedChannels); - } else if (Arrays.equals(UNSUBSCRIBE.getRaw(), resp)) { + } else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) { subscribedChannels = ((Long) reply.get(2)).intValue(); final byte[] bchannel = (byte[]) reply.get(1); onUnsubscribe(bchannel, subscribedChannels); - } else if (Arrays.equals(MESSAGE.getRaw(), resp)) { + } else if (Arrays.equals(MESSAGE.raw, resp)) { final byte[] bchannel = (byte[]) reply.get(1); final byte[] bmesg = (byte[]) reply.get(2); onMessage(bchannel, bmesg); - } else if (Arrays.equals(PMESSAGE.getRaw(), resp)) { + } else if (Arrays.equals(PMESSAGE.raw, resp)) { final byte[] bpattern = (byte[]) reply.get(1); final byte[] bchannel = (byte[]) reply.get(2); final byte[] bmesg = (byte[]) reply.get(3); onPMessage(bpattern, bchannel, bmesg); - } else if (Arrays.equals(PSUBSCRIBE.getRaw(), resp)) { + } else if (Arrays.equals(PSUBSCRIBE.raw, resp)) { subscribedChannels = ((Long) reply.get(2)).intValue(); final byte[] bpattern = (byte[]) reply.get(1); onPSubscribe(bpattern, subscribedChannels); - } else if (Arrays.equals(PUNSUBSCRIBE.getRaw(), resp)) { + } else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) { subscribedChannels = ((Long) reply.get(2)).intValue(); final byte[] bpattern = (byte[]) reply.get(1); onPUnsubscribe(bpattern, subscribedChannels); - } else if (Arrays.equals(PONG.getRaw(), resp)) { - final byte[] bpattern = (byte[]) reply.get(1); - onPong(bpattern); } else { throw new JedisException("Unknown message type: " + firstObj); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryShardedJedis.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryShardedJedis.java index 478a12438..9c70ce568 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryShardedJedis.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryShardedJedis.java @@ -1,37 +1,22 @@ package com.fr.third.redis.clients.jedis; +import java.util.Collection; 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 com.fr.third.redis.clients.jedis.commands.BinaryJedisCommands; -import com.fr.third.redis.clients.jedis.commands.ProtocolCommand; import com.fr.third.redis.clients.jedis.exceptions.JedisConnectionException; -import com.fr.third.redis.clients.jedis.params.GeoAddParams; import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; -import com.fr.third.redis.clients.jedis.params.GetExParams; -import com.fr.third.redis.clients.jedis.params.RestoreParams; import com.fr.third.redis.clients.jedis.params.SetParams; -import com.fr.third.redis.clients.jedis.params.XAddParams; -import com.fr.third.redis.clients.jedis.params.XClaimParams; -import com.fr.third.redis.clients.jedis.params.XPendingParams; -import com.fr.third.redis.clients.jedis.params.XTrimParams; import com.fr.third.redis.clients.jedis.params.ZAddParams; import com.fr.third.redis.clients.jedis.params.ZIncrByParams; -import com.fr.third.redis.clients.jedis.params.LPosParams; import com.fr.third.redis.clients.jedis.util.Hashing; import com.fr.third.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); } @@ -52,19 +37,14 @@ public class BinaryShardedJedis extends Sharded implement for (Jedis jedis : getAllShards()) { if (jedis.isConnected()) { try { - // need a proper test, probably with mock - if (!jedis.isBroken()) { - jedis.quit(); - } + 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); } } } @@ -92,18 +72,6 @@ public class BinaryShardedJedis extends Sharded implement 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); @@ -123,26 +91,13 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public String restore(final byte[] key, final long ttl, final byte[] serializedValue) { + public String restore(final byte[] key, final int 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) { + public Long expire(final byte[] key, final int seconds) { Jedis j = getShard(key); return j.expire(key, seconds); } @@ -196,7 +151,7 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public String setex(final byte[] key, final long seconds, final byte[] value) { + public String setex(final byte[] key, final int seconds, final byte[] value) { Jedis j = getShard(key); return j.setex(key, seconds, value); } @@ -334,7 +289,7 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public List hvals(final byte[] key) { + public Collection hvals(final byte[] key) { Jedis j = getShard(key); return j.hvals(key); } @@ -345,24 +300,6 @@ public class BinaryShardedJedis extends Sharded implement 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); @@ -441,43 +378,12 @@ public class BinaryShardedJedis extends Sharded implement 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); @@ -520,12 +426,6 @@ public class BinaryShardedJedis extends Sharded implement 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); @@ -533,7 +433,7 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public List srandmember(final byte[] key, final int count) { + public List srandmember(final byte[] key, final int count) { Jedis j = getShard(key); return j.srandmember(key, count); } @@ -545,8 +445,7 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public Long zadd(final byte[] key, final double score, final byte[] member, - final ZAddParams params) { + 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); } @@ -563,12 +462,6 @@ public class BinaryShardedJedis extends Sharded implement 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); @@ -588,8 +481,7 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public Double zincrby(final byte[] key, final double increment, final byte[] member, - ZIncrByParams params) { + 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); } @@ -624,24 +516,6 @@ public class BinaryShardedJedis extends Sharded implement 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); @@ -654,36 +528,6 @@ public class BinaryShardedJedis extends Sharded implement 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); @@ -715,8 +559,7 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public Set zrangeByScore(final byte[] key, final double min, final double max, - final int offset, final int count) { + 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); } @@ -728,8 +571,8 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public Set zrangeByScoreWithScores(final byte[] key, final double min, final double max, - final int offset, final int count) { + 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); } @@ -747,15 +590,14 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public Set zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max, - final int offset, final int count) { + 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) { + 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); } @@ -767,8 +609,7 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public Set zrevrangeByScore(final byte[] key, final double max, final double min, - final int offset, final int count) { + 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); } @@ -780,8 +621,8 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public Set zrevrangeByScoreWithScores(final byte[] key, final double max, - final double min, final int offset, final int count) { + 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); } @@ -793,8 +634,7 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public Set zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min, - final int offset, final int count) { + 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); } @@ -806,8 +646,8 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public Set zrevrangeByScoreWithScores(final byte[] key, final byte[] max, - final byte[] min, final int offset, final int count) { + 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); } @@ -856,8 +696,7 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public Set zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min, - final int offset, final int count) { + 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); } @@ -869,18 +708,11 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public Long linsert(final byte[] key, final ListPosition where, final byte[] pivot, - final byte[] value) { + 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); } - /** - * @return - * @deprecated The support of {@link ShardedJedisPipeline} and this method will be removed in next - * major release. - */ - @Deprecated public ShardedJedisPipeline pipelined() { ShardedJedisPipeline pipeline = new ShardedJedisPipeline(); pipeline.setShardedJedis(this); @@ -902,16 +734,6 @@ public class BinaryShardedJedis extends Sharded implement 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); @@ -989,8 +811,7 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public Long geoadd(final byte[] key, final double longitude, final double latitude, - final byte[] member) { + 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); } @@ -1001,12 +822,6 @@ public class BinaryShardedJedis extends Sharded implement 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); @@ -1014,8 +829,7 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public Double geodist(final byte[] key, final byte[] member1, final byte[] member2, - final GeoUnit unit) { + 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); } @@ -1033,61 +847,33 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public List georadius(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { + 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) { + 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) { + 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) { + 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) { Jedis j = getShard(key); @@ -1095,8 +881,7 @@ public class BinaryShardedJedis extends Sharded implement } @Override - public ScanResult> hscan(final byte[] key, final byte[] cursor, - final ScanParams params) { + public ScanResult> hscan(final byte[] key, final byte[] cursor, final ScanParams params) { Jedis j = getShard(key); return j.hscan(key, cursor, params); } @@ -1129,202 +914,12 @@ public class BinaryShardedJedis extends Sharded implement 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 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); - } - - 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); - } + } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BitPosParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BitPosParams.java index c79707f8b..cb6c549e0 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BitPosParams.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BitPosParams.java @@ -6,7 +6,7 @@ import java.util.Collections; import java.util.List; public class BitPosParams { - private List params = new ArrayList<>(); + private List params = new ArrayList(); protected BitPosParams() { } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BuilderFactory.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BuilderFactory.java index db1e6fbfd..b0f9ed233 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BuilderFactory.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BuilderFactory.java @@ -1,6 +1,5 @@ package com.fr.third.redis.clients.jedis; -import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -10,94 +9,10 @@ import java.util.List; import java.util.Map; import java.util.Set; -import com.fr.third.redis.clients.jedis.resps.*; import com.fr.third.redis.clients.jedis.util.JedisByteHashMap; import com.fr.third.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) { - return data; - } - - @Override - public String toString() { - return "Object"; - } - }; - - public static final Builder> RAW_OBJECT_LIST = new Builder>() { - @Override - public List build(Object data) { - return (List) data; - } - - @Override - public String toString() { - return "List"; - } - }; - - public static final Builder ENCODED_OBJECT = new Builder() { - @Override - public Object build(Object data) { - return SafeEncoder.encodeObject(data); - } - - @Override - public String toString() { - return "Object"; - } - }; - - public static final Builder LONG = new Builder() { - @Override - public Long build(Object data) { - return (Long) data; - } - - @Override - public String toString() { - return "long"; // TODO: Long - } - - }; - - public static final Builder> LONG_LIST = new Builder>() { - @Override - @SuppressWarnings("unchecked") - public List build(Object data) { - if (null == data) { - return null; - } - return (List) data; - } - - @Override - public String toString() { - return "List"; - } - - }; - public static final Builder DOUBLE = new Builder() { @Override public Double build(Object data) { @@ -114,106 +29,70 @@ public final class BuilderFactory { @Override public String toString() { - return "double"; // TODO: Double - } - }; - - public static final Builder> DOUBLE_LIST = new Builder>() { - @Override - @SuppressWarnings("unchecked") - public List build(Object data) { - if (null == data) { - return null; - } - List values = (List) data; - List doubles = new ArrayList<>(values.size()); - for (byte[] value : values) { - doubles.add(DOUBLE.build(value)); - } - return doubles; - } - - @Override - public String toString() { - return "List"; + return "double"; } }; - public static final Builder BOOLEAN = new Builder() { @Override public Boolean build(Object data) { - return ((Long) data) == 1L; + return ((Long) data) == 1; } @Override public String toString() { - return "boolean"; // Boolean? + return "boolean"; } }; - - public static final Builder> BOOLEAN_LIST = new Builder>() { + public static final Builder BYTE_ARRAY = new Builder() { @Override - @SuppressWarnings("unchecked") - public List build(Object data) { - if (null == data) { - return null; - } - List longs = (List) data; - List booleans = new ArrayList<>(longs.size()); - for (Long value : longs) { - booleans.add(value == 1L); - } - return booleans; + public byte[] build(Object data) { + return ((byte[]) data); // deleted == 1 } @Override public String toString() { - return "List"; + return "byte[]"; } }; - public static final Builder BYTE_ARRAY = new Builder() { + public static final Builder LONG = new Builder() { @Override - public byte[] build(Object data) { - return ((byte[]) data); + public Long build(Object data) { + return (Long) data; } @Override public String toString() { - return "byte[]"; + return "long"; } - }; - public static final Builder> BYTE_ARRAY_LIST = new Builder>() { + }; + public static final Builder STRING = new Builder() { @Override - @SuppressWarnings("unchecked") - public List build(Object data) { - if (null == data) { - return null; - } - return (List) data; + public String build(Object data) { + return data == null ? null : SafeEncoder.encode((byte[]) data); } @Override public String toString() { - return "List"; + return "string"; } - }; - public static final Builder> BYTE_ARRAY_ZSET = new Builder>() { + }; + public static final Builder> STRING_LIST = new Builder>() { @Override @SuppressWarnings("unchecked") - public Set build(Object data) { + public List build(Object data) { if (null == data) { return null; } List l = (List) data; - final Set result = new LinkedHashSet<>(l); + final ArrayList result = new ArrayList(l.size()); for (final byte[] barray : l) { if (barray == null) { result.add(null); } else { - result.add(barray); + result.add(SafeEncoder.encode(barray)); } } return result; @@ -221,18 +100,19 @@ public final class BuilderFactory { @Override public String toString() { - return "ZSet"; + return "List"; } + }; - public static final Builder> BYTE_ARRAY_MAP = new Builder>() { + public static final Builder> STRING_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 JedisByteHashMap(); + final Map hash = new HashMap(flatHash.size()/2, 1); final Iterator iterator = flatHash.iterator(); while (iterator.hasNext()) { - hash.put(iterator.next(), iterator.next()); + hash.put(SafeEncoder.encode(iterator.next()), SafeEncoder.encode(iterator.next())); } return hash; @@ -240,33 +120,42 @@ public final class BuilderFactory { @Override public String toString() { - return "Map"; + return "Map"; } }; - public static final Builder STRING = new Builder() { + public static final Builder> PUBSUB_NUMSUB_MAP = new Builder>() { @Override - public String build(Object data) { - return data == null ? null : SafeEncoder.encode((byte[]) data); + @SuppressWarnings("unchecked") + public Map build(Object data) { + final List flatHash = (List) data; + 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())); + } + + return hash; } @Override public String toString() { - return "string"; // TODO: String + return "PUBSUB_NUMSUB_MAP"; } }; - public static final Builder> STRING_LIST = new Builder>() { + public static final Builder> STRING_SET = new Builder>() { @Override @SuppressWarnings("unchecked") - public List build(Object data) { + public Set build(Object data) { if (null == data) { return null; } List l = (List) data; - final ArrayList result = new ArrayList<>(l.size()); + final Set result = new HashSet(l.size(), 1); for (final byte[] barray : l) { if (barray == null) { result.add(null); @@ -279,51 +168,43 @@ public final class BuilderFactory { @Override public String toString() { - return "List"; + return "Set"; } }; - public static final Builder> STRING_SET = new Builder>() { + public static final Builder> BYTE_ARRAY_LIST = new Builder>() { @Override @SuppressWarnings("unchecked") - public Set build(Object data) { + public List build(Object data) { if (null == data) { return null; } List l = (List) data; - final Set result = new HashSet<>(l.size(), 1); - for (final byte[] barray : l) { - if (barray == null) { - result.add(null); - } else { - result.add(SafeEncoder.encode(barray)); - } - } - return result; + + return l; } @Override public String toString() { - return "Set"; + return "List"; } - }; - public static final Builder> STRING_ZSET = new Builder>() { + public static final Builder> BYTE_ARRAY_ZSET = new Builder>() { @Override @SuppressWarnings("unchecked") - public Set build(Object data) { + public Set build(Object data) { if (null == data) { return null; } List l = (List) data; - final Set result = new LinkedHashSet<>(l.size(), 1); + final Set result = new LinkedHashSet(l); for (final byte[] barray : l) { if (barray == null) { result.add(null); } else { - result.add(SafeEncoder.encode(barray)); + result.add(barray); } } return result; @@ -331,20 +212,18 @@ public final class BuilderFactory { @Override public String toString() { - return "ZSet"; + return "ZSet"; } - }; - - public static final Builder> STRING_MAP = new Builder>() { + public static final Builder> BYTE_ARRAY_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 JedisByteHashMap(); final Iterator iterator = flatHash.iterator(); while (iterator.hasNext()) { - hash.put(SafeEncoder.encode(iterator.next()), SafeEncoder.encode(iterator.next())); + hash.put(iterator.next(), iterator.next()); } return hash; @@ -352,59 +231,35 @@ public final class BuilderFactory { @Override public String toString() { - return "Map"; - } - - }; - - public static final Builder KEYED_LIST_ELEMENT = new Builder() { - @Override - @SuppressWarnings("unchecked") - public KeyedListElement build(Object data) { - if (data == null) return null; - List l = (List) data; - return new KeyedListElement(l.get(0), l.get(1)); + return "Map"; } - @Override - public String toString() { - return "KeyedListElement"; - } }; - public static final Builder TUPLE = new Builder() { + public static final Builder> STRING_ZSET = new Builder>() { @Override @SuppressWarnings("unchecked") - public Tuple build(Object data) { - List l = (List) data; // never null - if (l.isEmpty()) { + public Set build(Object data) { + if (null == data) { return null; } - return new Tuple(l.get(0), DOUBLE.build(l.get(1))); - } - - @Override - public String toString() { - return "Tuple"; - } - - }; - - public static final Builder KEYED_ZSET_ELEMENT = new Builder() { - @Override - @SuppressWarnings("unchecked") - public KeyedZSetElement build(Object data) { - List l = (List) data; // never null - if (l.isEmpty()) { - 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 new KeyedZSetElement(l.get(0), l.get(1), DOUBLE.build(l.get(2))); + return result; } @Override public String toString() { - return "KeyedZSetElement"; + return "ZSet"; } + }; public static final Builder> TUPLE_ZSET = new Builder>() { @@ -415,7 +270,7 @@ public final class BuilderFactory { return null; } List l = (List) data; - final Set result = new LinkedHashSet<>(l.size() / 2, 1); + final Set result = new LinkedHashSet(l.size()/2, 1); Iterator iterator = l.iterator(); while (iterator.hasNext()) { result.add(new Tuple(iterator.next(), DOUBLE.build(iterator.next()))); @@ -430,59 +285,62 @@ public final class BuilderFactory { }; - /** - * @deprecated Use {@link #ENCODED_OBJECT}. - */ - @Deprecated public static final Builder EVAL_RESULT = new Builder() { @Override public Object build(Object data) { - return SafeEncoder.encodeObject(data); + return evalResult(data); } @Override public String toString() { return "Eval"; } + + private Object evalResult(Object result) { + if (result instanceof byte[]) return SafeEncoder.encode((byte[]) result); + + if (result instanceof List) { + List list = (List) result; + List listResult = new ArrayList(list.size()); + for (Object bin : list) { + listResult.add(evalResult(bin)); + } + + return listResult; + } + + return result; + } + }; - /** - * @deprecated Use {@link #RAW_OBJECT}. - */ - @Deprecated public static final Builder EVAL_BINARY_RESULT = new Builder() { @Override public Object build(Object data) { - return data; + return evalResult(data); } @Override public String toString() { return "Eval"; } - }; - public static final Builder> PUBSUB_NUMSUB_MAP = new Builder>() { - @Override - @SuppressWarnings("unchecked") - public Map build(Object data) { - final List flatHash = (List) data; - 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())); + private Object evalResult(Object result) { + if (result instanceof List) { + List list = (List) result; + List listResult = new ArrayList(list.size()); + for (Object bin : list) { + listResult.add(evalResult(bin)); + } + + return listResult; } - return hash; + return result; } - @Override - public String toString() { - return "PUBSUB_NUMSUB_MAP"; - } }; public static final Builder> GEO_COORDINATE_LIST = new Builder>() { @@ -500,7 +358,7 @@ public final class BuilderFactory { } private List interpretGeoposResult(List responses) { - List responseCoordinate = new ArrayList<>(responses.size()); + List responseCoordinate = new ArrayList(responses.size()); for (Object response : responses) { if (response == null) { responseCoordinate.add(null); @@ -524,7 +382,7 @@ public final class BuilderFactory { List objectList = (List) data; - List responses = new ArrayList<>(objectList.size()); + List responses = new ArrayList(objectList.size()); if (objectList.isEmpty()) { return responses; } @@ -546,9 +404,6 @@ public final class BuilderFactory { resp.setCoordinate(new GeoCoordinate(DOUBLE.build(coord.get(0)), DOUBLE.build(coord.get(1)))); - } else if (info instanceof Long) { - // score - resp.setRawScore(LONG.build(info)); } else { // distance resp.setDistance(DOUBLE.build(info)); @@ -573,6 +428,7 @@ public final class BuilderFactory { } }; + public static final Builder> MODULE_LIST = new Builder>() { @Override public List build(Object data) { @@ -582,14 +438,13 @@ public final class BuilderFactory { List> objectList = (List>) data; - List responses = new ArrayList<>(objectList.size()); + List responses = new ArrayList(objectList.size()); if (objectList.isEmpty()) { return responses; } - for (List moduleResp : objectList) { - Module m = new Module(SafeEncoder.encode((byte[]) moduleResp.get(1)), - ((Long) moduleResp.get(3)).intValue()); + for (List moduleResp: objectList) { + Module m = new Module(SafeEncoder.encode((byte[]) moduleResp.get(1)), ((Long) moduleResp.get(3)).intValue()); responses.add(m); } @@ -602,445 +457,26 @@ public final class BuilderFactory { } }; - /** - * Create a AccessControlUser object from the ACL GETUSER < > result - */ - public static final Builder ACCESS_CONTROL_USER = new Builder() { - @Override - public AccessControlUser build(Object data) { - if (data == null) { - return null; - } - - List> objectList = (List>) data; - if (objectList.isEmpty()) { - return null; - } - - AccessControlUser accessControlUser = new AccessControlUser(); - - // flags - List flags = objectList.get(1); - for (Object f : flags) { - accessControlUser.addFlag(SafeEncoder.encode((byte[]) f)); - } - - // passwords - List passwords = objectList.get(3); - for (Object p : passwords) { - accessControlUser.addPassword(SafeEncoder.encode((byte[]) p)); - } - - // commands - accessControlUser.setCommands(SafeEncoder.encode((byte[]) (Object) objectList.get(5))); - - // keys - List keys = objectList.get(7); - for (Object k : keys) { - accessControlUser.addKey(SafeEncoder.encode((byte[]) k)); - } - - return accessControlUser; - } - - @Override - public String toString() { - return "AccessControlUser"; - } - - }; - - /** - * Create an Access Control Log Entry Result of ACL LOG command - */ - public static final Builder> ACCESS_CONTROL_LOG_ENTRY_LIST = new Builder>() { - - private final Map mappingFunctions = createDecoderMap(); - - private Map createDecoderMap() { - - Map tempMappingFunctions = new HashMap<>(); - tempMappingFunctions.put(AccessControlLogEntry.COUNT, LONG); - tempMappingFunctions.put(AccessControlLogEntry.REASON, STRING); - tempMappingFunctions.put(AccessControlLogEntry.CONTEXT, STRING); - tempMappingFunctions.put(AccessControlLogEntry.OBJECT, STRING); - tempMappingFunctions.put(AccessControlLogEntry.USERNAME, STRING); - tempMappingFunctions.put(AccessControlLogEntry.AGE_SECONDS, STRING); - tempMappingFunctions.put(AccessControlLogEntry.CLIENT_INFO, STRING); - - return tempMappingFunctions; - } - - @Override - public List build(Object data) { - - if (null == data) { - return null; - } - - List list = new ArrayList<>(); - List> logEntries = (List>) data; - for (List logEntryData : logEntries) { - Iterator logEntryDataIterator = logEntryData.iterator(); - AccessControlLogEntry accessControlLogEntry = new AccessControlLogEntry( - createMapFromDecodingFunctions(logEntryDataIterator, mappingFunctions)); - list.add(accessControlLogEntry); - } - return list; - } - - @Override - public String toString() { - return "List"; - } - }; - - // Stream Builders --> - - public static final Builder STREAM_ENTRY_ID = new Builder() { - @Override - public StreamEntryID build(Object data) { - if (null == data) { - return null; - } - String id = SafeEncoder.encode((byte[]) data); - return new StreamEntryID(id); - } - - @Override - public String toString() { - return "StreamEntryID"; - } - }; - - public static final Builder> STREAM_ENTRY_ID_LIST = new Builder>() { - @Override - @SuppressWarnings("unchecked") - public List build(Object data) { - if (null == data) { - return null; - } - List objectList = (List) data; - List responses = new ArrayList<>(objectList.size()); - if (!objectList.isEmpty()) { - for(Object object : objectList) { - responses.add(STREAM_ENTRY_ID.build(object)); - } - } - return responses; - } - }; - - public static final Builder STREAM_ENTRY = new Builder() { - @Override - @SuppressWarnings("unchecked") - public StreamEntry build(Object data) { - if (null == data) { - return null; - } - List objectList = (List) data; - - if (objectList.isEmpty()) { - return null; - } - - String entryIdString = SafeEncoder.encode((byte[]) objectList.get(0)); - StreamEntryID entryID = new StreamEntryID(entryIdString); - List hash = (List) objectList.get(1); - - Iterator hashIterator = hash.iterator(); - Map map = new HashMap<>(hash.size() / 2); - while (hashIterator.hasNext()) { - map.put(SafeEncoder.encode(hashIterator.next()), SafeEncoder.encode(hashIterator.next())); - } - return new StreamEntry(entryID, map); - } - - @Override - public String toString() { - return "StreamEntry"; - } - }; - - public static final Builder> STREAM_ENTRY_LIST = new Builder>() { - @Override - @SuppressWarnings("unchecked") - public List build(Object data) { - if (null == data) { - return null; - } - List> objectList = (List>) data; - - List responses = new ArrayList<>(objectList.size() / 2); - if (objectList.isEmpty()) { - return responses; - } - - for (ArrayList res : objectList) { - if (res == null) { - responses.add(null); - continue; - } - String entryIdString = SafeEncoder.encode((byte[]) res.get(0)); - StreamEntryID entryID = new StreamEntryID(entryIdString); - List hash = (List) res.get(1); - - Iterator hashIterator = hash.iterator(); - Map map = new HashMap<>(hash.size() / 2); - while (hashIterator.hasNext()) { - map.put(SafeEncoder.encode(hashIterator.next()), SafeEncoder.encode(hashIterator.next())); - } - responses.add(new StreamEntry(entryID, map)); - } - - return responses; - } - - @Override - public String toString() { - return "List"; - } - }; - - public static final Builder>>> STREAM_READ_RESPONSE - = new Builder>>>() { - @Override - public List>> build(Object data) { - if (data == null) { - return null; - } - List streams = (List) data; - - List>> result = new ArrayList<>(streams.size()); - for (Object streamObj : streams) { - List stream = (List) streamObj; - String streamId = SafeEncoder.encode((byte[]) stream.get(0)); - List streamEntries = BuilderFactory.STREAM_ENTRY_LIST.build(stream.get(1)); - result.add(new AbstractMap.SimpleEntry<>(streamId, streamEntries)); - } - - return result; - } - - @Override - public String toString() { - return "List>>"; - } - }; - - public static final Builder> STREAM_PENDING_ENTRY_LIST = new Builder>() { - @Override - @SuppressWarnings("unchecked") - public List build(Object data) { - if (null == data) { - return null; - } - - List streamsEntries = (List) data; - List result = new ArrayList<>(streamsEntries.size()); - for (Object streamObj : streamsEntries) { - List stream = (List) streamObj; - String id = SafeEncoder.encode((byte[]) stream.get(0)); - String consumerName = SafeEncoder.encode((byte[]) stream.get(1)); - long idleTime = BuilderFactory.LONG.build(stream.get(2)); - long deliveredTimes = BuilderFactory.LONG.build(stream.get(3)); - result.add(new StreamPendingEntry(new StreamEntryID(id), consumerName, idleTime, - deliveredTimes)); - } - return result; - } - - @Override - public String toString() { - return "List"; - } - }; - - public static final Builder STREAM_INFO = new Builder() { - - Map mappingFunctions = createDecoderMap(); - - private Map createDecoderMap() { - - Map tempMappingFunctions = new HashMap<>(); - tempMappingFunctions.put(StreamInfo.LAST_GENERATED_ID, STREAM_ENTRY_ID); - tempMappingFunctions.put(StreamInfo.FIRST_ENTRY, STREAM_ENTRY); - tempMappingFunctions.put(StreamInfo.LENGTH, LONG); - tempMappingFunctions.put(StreamInfo.RADIX_TREE_KEYS, LONG); - tempMappingFunctions.put(StreamInfo.RADIX_TREE_NODES, LONG); - tempMappingFunctions.put(StreamInfo.LAST_ENTRY, STREAM_ENTRY); - tempMappingFunctions.put(StreamInfo.GROUPS, LONG); - - return tempMappingFunctions; - } - - @Override - @SuppressWarnings("unchecked") - public StreamInfo build(Object data) { - if (null == data) { - return null; - } - - List streamsEntries = (List) data; - Iterator iterator = streamsEntries.iterator(); - - return new StreamInfo(createMapFromDecodingFunctions(iterator, mappingFunctions)); - } - - @Override - public String toString() { - return "StreamInfo"; - } - }; - - public static final Builder> STREAM_GROUP_INFO_LIST = new Builder>() { - - Map mappingFunctions = createDecoderMap(); - - private Map createDecoderMap() { - - Map tempMappingFunctions = new HashMap<>(); - tempMappingFunctions.put(StreamGroupInfo.NAME, STRING); - tempMappingFunctions.put(StreamGroupInfo.CONSUMERS, LONG); - tempMappingFunctions.put(StreamGroupInfo.PENDING, LONG); - tempMappingFunctions.put(StreamGroupInfo.LAST_DELIVERED, STREAM_ENTRY_ID); - - return tempMappingFunctions; - } - - @Override - @SuppressWarnings("unchecked") - public List build(Object data) { - if (null == data) { - return null; - } - - List list = new ArrayList<>(); - List streamsEntries = (List) data; - Iterator groupsArray = streamsEntries.iterator(); - - while (groupsArray.hasNext()) { - - List groupInfo = (List) groupsArray.next(); - - Iterator groupInfoIterator = groupInfo.iterator(); - - StreamGroupInfo streamGroupInfo = new StreamGroupInfo(createMapFromDecodingFunctions( - groupInfoIterator, mappingFunctions)); - list.add(streamGroupInfo); - - } - return list; - - } - - @Override - public String toString() { - return "List"; - } - }; - - public static final Builder> STREAM_CONSUMERS_INFO_LIST = new Builder>() { - - Map mappingFunctions = createDecoderMap(); - - private Map createDecoderMap() { - Map tempMappingFunctions = new HashMap<>(); - tempMappingFunctions.put(StreamConsumersInfo.NAME, STRING); - tempMappingFunctions.put(StreamConsumersInfo.IDLE, LONG); - tempMappingFunctions.put(StreamGroupInfo.PENDING, LONG); - tempMappingFunctions.put(StreamGroupInfo.LAST_DELIVERED, STRING); - return tempMappingFunctions; - - } - + public static final Builder> LONG_LIST = new Builder>() { @Override @SuppressWarnings("unchecked") - public List build(Object data) { + public List build(Object data) { if (null == data) { return null; } - - List list = new ArrayList<>(); - List streamsEntries = (List) data; - Iterator groupsArray = streamsEntries.iterator(); - - while (groupsArray.hasNext()) { - - List groupInfo = (List) groupsArray.next(); - - Iterator consumerInfoIterator = groupInfo.iterator(); - - StreamConsumersInfo streamGroupInfo = new StreamConsumersInfo( - createMapFromDecodingFunctions(consumerInfoIterator, mappingFunctions)); - list.add(streamGroupInfo); - - } - return list; - + return (List) data; } @Override public String toString() { - return "List"; - } - }; - - public static final Builder STREAM_PENDING_SUMMARY = new Builder() { - @Override - @SuppressWarnings("unchecked") - public StreamPendingSummary build(Object data) { - if (null == data) { - return null; - } - - List objectList = (List) data; - long total = BuilderFactory.LONG.build(objectList.get(0)); - String minId = SafeEncoder.encode((byte[]) objectList.get(1)); - String maxId = SafeEncoder.encode((byte[]) objectList.get(2)); - List> consumerObjList = (List>) objectList.get(3); - Map map = new HashMap<>(consumerObjList.size()); - for (List consumerObj : consumerObjList) { - map.put(SafeEncoder.encode((byte[]) consumerObj.get(0)), Long.parseLong(SafeEncoder.encode((byte[]) consumerObj.get(1)))); - } - return new StreamPendingSummary(total, new StreamEntryID(minId), new StreamEntryID(maxId), map); + return "List"; } - @Override - public String toString() { - return "StreamPendingSummary"; - } }; - private static Map createMapFromDecodingFunctions(Iterator iterator, - Map mappingFunctions) { - - Map resultMap = new HashMap<>(); - while (iterator.hasNext()) { - - String mapKey = STRING.build(iterator.next()); - if (mappingFunctions.containsKey(mapKey)) { - resultMap.put(mapKey, mappingFunctions.get(mapKey).build(iterator.next())); - } else { // For future - if we don't find an element in our builder map - Object unknownData = iterator.next(); - for (Builder b : mappingFunctions.values()) { - try { - resultMap.put(mapKey, b.build(unknownData)); - break; - } catch (ClassCastException e) { - // We continue with next builder - - } - } - } - } - return resultMap; - } - - // <-- Stream Builders private BuilderFactory() { - throw new InstantiationError("Must not instantiate this class"); + throw new InstantiationError( "Must not instantiate this class" ); } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Client.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Client.java index 429a93e21..7694c0504 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Client.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Client.java @@ -2,7 +2,9 @@ package com.fr.third.redis.clients.jedis; import static com.fr.third.redis.clients.jedis.Protocol.toByteArray; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -10,9 +12,11 @@ import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocketFactory; -import com.fr.third.redis.clients.jedis.args.ListDirection; import com.fr.third.redis.clients.jedis.commands.Commands; -import com.fr.third.redis.clients.jedis.params.*; +import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; +import com.fr.third.redis.clients.jedis.params.SetParams; +import com.fr.third.redis.clients.jedis.params.ZAddParams; +import com.fr.third.redis.clients.jedis.params.ZIncrByParams; import com.fr.third.redis.clients.jedis.util.SafeEncoder; public class Client extends BinaryClient implements Commands { @@ -21,12 +25,6 @@ public class Client extends BinaryClient implements Commands { 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); } @@ -35,47 +33,16 @@ public class Client extends BinaryClient implements Commands { 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)); @@ -91,16 +58,6 @@ public class Client extends BinaryClient implements Commands { 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)); @@ -137,7 +94,7 @@ public class Client extends BinaryClient implements Commands { } @Override - public void expire(final String key, final long seconds) { + public void expire(final String key, final int seconds) { expire(SafeEncoder.encode(key), seconds); } @@ -177,7 +134,7 @@ public class Client extends BinaryClient implements Commands { } @Override - public void setex(final String key, final long seconds, final String value) { + public void setex(final String key, final int seconds, final String value) { setex(SafeEncoder.encode(key), seconds, SafeEncoder.encode(value)); } @@ -228,7 +185,7 @@ public class Client extends BinaryClient implements Commands { @Override public void hset(final String key, final Map hash) { - final Map bhash = new HashMap<>(hash.size()); + final Map bhash = new HashMap(hash.size()); for (final Entry entry : hash.entrySet()) { bhash.put(SafeEncoder.encode(entry.getKey()), SafeEncoder.encode(entry.getValue())); } @@ -247,7 +204,7 @@ public class Client extends BinaryClient implements Commands { @Override public void hmset(final String key, final Map hash) { - final Map bhash = new HashMap<>(hash.size()); + final Map bhash = new HashMap(hash.size()); for (final Entry entry : hash.entrySet()) { bhash.put(SafeEncoder.encode(entry.getKey()), SafeEncoder.encode(entry.getValue())); } @@ -294,21 +251,6 @@ public class Client extends BinaryClient implements Commands { 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)); @@ -354,36 +296,11 @@ public class Client extends BinaryClient implements Commands { 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)); @@ -429,11 +346,6 @@ public class Client extends BinaryClient implements Commands { 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)); @@ -492,21 +404,6 @@ public class Client extends BinaryClient implements Commands { 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); @@ -523,8 +420,7 @@ public class Client extends BinaryClient implements Commands { } @Override - public void zincrby(final String key, final double increment, final String member, - final ZIncrByParams params) { + public void zincrby(final String key, final double increment, final String member, final ZIncrByParams params) { zincrby(SafeEncoder.encode(key), increment, SafeEncoder.encode(member), params); } @@ -553,21 +449,6 @@ public class Client extends BinaryClient implements Commands { 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)); @@ -578,31 +459,6 @@ public class Client extends BinaryClient implements Commands { 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)); @@ -618,65 +474,44 @@ public class Client extends BinaryClient implements Commands { 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)); + final int size = keys.length + 1; + List args = new ArrayList(size); + for (String arg : keys) { + args.add(arg); + } + args.add(String.valueOf(timeout)); + blpop(args.toArray(new String[size])); } @Override - public void brpop(final int timeout, final String... keys) { - brpop(timeout, SafeEncoder.encodeMany(keys)); + public void sort(final String key, final SortingParams sortingParameters, final String dstkey) { + sort(SafeEncoder.encode(key), sortingParameters, SafeEncoder.encode(dstkey)); } @Override - public void brpop(final double timeout, final String... keys) { - brpop(timeout, SafeEncoder.encodeMany(keys)); + public void sort(final String key, final String dstkey) { + sort(SafeEncoder.encode(key), SafeEncoder.encode(dstkey)); } @Override - public void bzpopmax(final double timeout, final String... keys) { - bzpopmax(timeout, SafeEncoder.encodeMany(keys)); + public void brpop(final String[] args) { + brpop(SafeEncoder.encodeMany(args)); } - @Override - public void bzpopmin(final double timeout, final String... keys) { - bzpopmin(timeout, SafeEncoder.encodeMany(keys)); + public void brpop(final int timeout, final String... keys) { + final int size = keys.length + 1; + List args = new ArrayList(size); + for (String arg : keys) { + args.add(arg); + } + args.add(String.valueOf(timeout)); + brpop(args.toArray(new String[size])); } @Override @@ -689,11 +524,6 @@ public class Client extends BinaryClient implements Commands { 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)); @@ -805,16 +635,6 @@ public class Client extends BinaryClient implements Commands { 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)); @@ -825,16 +645,6 @@ public class Client extends BinaryClient implements Commands { 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)); @@ -863,8 +673,7 @@ public class Client extends BinaryClient implements Commands { 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) { + 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); } @@ -1011,11 +820,6 @@ public class Client extends BinaryClient implements Commands { 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)); @@ -1035,27 +839,14 @@ public class Client extends BinaryClient implements Commands { sentinel(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) { + public void restore(final String key, final int 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); } @@ -1082,32 +873,17 @@ public class Client extends BinaryClient implements Commands { 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 clientKill(final String client) { + clientKill(SafeEncoder.encode(client)); } 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)); + migrate(SafeEncoder.encode(host), port, SafeEncoder.encode(key), destinationDb, timeout); } @Override @@ -1267,8 +1043,7 @@ public class Client extends BinaryClient implements Commands { cluster(Protocol.CLUSTER_SLOTS); } - public void geoadd(final String key, final double longitude, final double latitude, - final String member) { + public void geoadd(final String key, final double longitude, final double latitude, final String member) { geoadd(SafeEncoder.encode(key), longitude, latitude, SafeEncoder.encode(member)); } @@ -1276,16 +1051,11 @@ public class Client extends BinaryClient implements Commands { 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) { + 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); } @@ -1297,59 +1067,24 @@ public class Client extends BinaryClient implements Commands { 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) { + 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) { + 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) { + 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) { + 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)); } @@ -1358,32 +1093,8 @@ public class Client extends BinaryClient implements Commands { 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<>(); + HashMap binaryScoreMembers = new HashMap(); for (Entry entry : scoreMembers.entrySet()) { binaryScoreMembers.put(SafeEncoder.encode(entry.getKey()), entry.getValue()); } @@ -1392,7 +1103,7 @@ public class Client extends BinaryClient implements Commands { private HashMap convertMemberCoordinateMapToBinary( final Map memberCoordinateMap) { - HashMap binaryMemberCoordinateMap = new HashMap<>(); + HashMap binaryMemberCoordinateMap = new HashMap(); for (Entry entry : memberCoordinateMap.entrySet()) { binaryMemberCoordinateMap.put(SafeEncoder.encode(entry.getKey()), entry.getValue()); } @@ -1404,250 +1115,9 @@ public class Client extends BinaryClient implements Commands { 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.raw; - 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.raw; - args[index++] = SafeEncoder.encode(groupname); - args[index++] = SafeEncoder.encode(consumer); - System.arraycopy(bparams, 0, args, index, paramLength); - index += paramLength; - - args[index++] = Protocol.Keyword.STREAMS.raw; - 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 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/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Connection.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Connection.java index 187d8658a..36a0b3198 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Connection.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Connection.java @@ -2,6 +2,7 @@ package com.fr.third.redis.clients.jedis; import java.io.Closeable; import java.io.IOException; +import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; @@ -9,6 +10,7 @@ import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import com.fr.third.redis.clients.jedis.commands.ProtocolCommand; @@ -23,67 +25,46 @@ 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 String host = Protocol.DEFAULT_HOST; + private int port = Protocol.DEFAULT_PORT; private Socket socket; private RedisOutputStream outputStream; private RedisInputStream inputStream; + private int connectionTimeout = Protocol.DEFAULT_TIMEOUT; private int soTimeout = Protocol.DEFAULT_TIMEOUT; - private int infiniteSoTimeout = 0; private boolean broken = false; + private boolean ssl; + private SSLSocketFactory sslSocketFactory; + private SSLParameters sslParameters; + private HostnameVerifier hostnameVerifier; 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); + this.host = host; } public Connection(final String host, final int port) { - this(new HostAndPort(host, port), DefaultJedisClientConfig.builder().build()); + this.host = host; + this.port = port; } - /** - * @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.host = host; + this.port = port; + this.ssl = ssl; } - /** - * @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, final JedisClientConfig clientConfig) { - this(new DefaultJedisSocketFactory(hostAndPort, clientConfig)); - this.soTimeout = clientConfig.getSocketTimeoutMillis(); - this.infiniteSoTimeout = clientConfig.getBlockingSocketTimeoutMillis(); - } - - public Connection(final JedisSocketFactory jedisSocketFactory) { - this.socketFactory = jedisSocketFactory; - this.soTimeout = jedisSocketFactory.getSoTimeout(); - } - - @Override - public String toString() { - return "Connection{" + socketFactory + "}"; + this.host = host; + this.port = port; + this.ssl = ssl; + this.sslSocketFactory = sslSocketFactory; + this.sslParameters = sslParameters; + this.hostnameVerifier = hostnameVerifier; } public Socket getSocket() { @@ -91,38 +72,19 @@ public class Connection implements Closeable { } public int getConnectionTimeout() { - return socketFactory.getConnectionTimeout(); + return connectionTimeout; } 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); + this.connectionTimeout = connectionTimeout; } public void setSoTimeout(int soTimeout) { - socketFactory.setSoTimeout(soTimeout); this.soTimeout = soTimeout; - if (this.socket != null) { - try { - this.socket.setSoTimeout(soTimeout); - } catch (SocketException ex) { - broken = true; - throw new JedisConnectionException(ex); - } - } - } - - public void setInfiniteSoTimeout(int infiniteSoTimeout) { - this.infiniteSoTimeout = infiniteSoTimeout; } public void setTimeoutInfinite() { @@ -130,7 +92,7 @@ public class Connection implements Closeable { if (!isConnected()) { connect(); } - socket.setSoTimeout(infiniteSoTimeout); + socket.setSoTimeout(0); } catch (SocketException ex) { broken = true; throw new JedisConnectionException(ex); @@ -139,7 +101,7 @@ public class Connection implements Closeable { public void rollbackTimeout() { try { - socket.setSoTimeout(socketFactory.getSoTimeout()); + socket.setSoTimeout(soTimeout); } catch (SocketException ex) { broken = true; throw new JedisConnectionException(ex); @@ -186,57 +148,61 @@ public class Connection implements Closeable { } public String getHost() { - return socketFactory.getHost(); + return host; } - /** - * @param host - * @deprecated This method will be removed in future. - */ - @Deprecated public void setHost(final String host) { - socketFactory.setHost(host); - socketParamModified = true; + this.host = host; } public int getPort() { - return socketFactory.getPort(); + return port; } - /** - * @param port - * @deprecated This method will be removed in future. - */ - @Deprecated public void setPort(final int port) { - socketFactory.setPort(port); - socketParamModified = true; + this.port = port; } - public void connect() throws JedisConnectionException { - if (socketParamModified) { // this is only for backward compatibility - try { - disconnect(); - } catch (Exception e) { - // swallow - } - } + public void connect() { if (!isConnected()) { try { - socket = socketFactory.createSocket(); + 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 + + socket.connect(new InetSocketAddress(host, port), connectionTimeout); + socket.setSoTimeout(soTimeout); + + if (ssl) { + if (null == sslSocketFactory) { + sslSocketFactory = (SSLSocketFactory)SSLSocketFactory.getDefault(); + } + socket = sslSocketFactory.createSocket(socket, host, port, true); + if (null != sslParameters) { + ((SSLSocket) socket).setSSLParameters(sslParameters); + } + if ((null != hostnameVerifier) && + (!hostnameVerifier.verify(host, ((SSLSocket) socket).getSession()))) { + String message = String.format( + "The connection to '%s' failed ssl/tls hostname verification.", host); + throw new JedisConnectionException(message); + } + } 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) { + } catch (IOException ex) { broken = true; - throw jce; - } finally { - if (broken) { - IOUtils.closeQuietly(socket); - } + throw new JedisConnectionException("Failed connecting to host " + + host + ":" + port, ex); } } } @@ -304,9 +270,10 @@ public class Connection implements Closeable { return (List) readProtocolWithCheckingBroken(); } - @Deprecated + @SuppressWarnings("unchecked") public List getRawObjectMultiBulkReply() { - return getUnflushedObjectMultiBulkReply(); + flush(); + return (List) readProtocolWithCheckingBroken(); } @SuppressWarnings("unchecked") @@ -315,8 +282,7 @@ public class Connection implements Closeable { } public List getObjectMultiBulkReply() { - flush(); - return getUnflushedObjectMultiBulkReply(); + return getRawObjectMultiBulkReply(); } @SuppressWarnings("unchecked") @@ -344,10 +310,6 @@ public class Connection implements Closeable { } protected Object readProtocolWithCheckingBroken() { - if (broken) { - throw new JedisConnectionException("Attempting to read from a broken connection"); - } - try { return Protocol.read(inputStream); } catch (JedisConnectionException exc) { @@ -358,7 +320,7 @@ public class Connection implements Closeable { public List getMany(final int count) { flush(); - final List responses = new ArrayList<>(count); + final List responses = new ArrayList(count); for (int i = 0; i < count; i++) { try { responses.add(readProtocolWithCheckingBroken()); diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/DebugParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/DebugParams.java index b1f7cc036..24bf6f03e 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/DebugParams.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/DebugParams.java @@ -1,16 +1,16 @@ package com.fr.third.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" }; diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/DefaultJedisClientConfig.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/DefaultJedisClientConfig.java deleted file mode 100644 index 02f74296e..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/DefaultJedisClientConfig.java +++ /dev/null @@ -1,210 +0,0 @@ -package com.fr.third.redis.clients.jedis; - -import java.util.Objects; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLParameters; -import javax.net.ssl.SSLSocketFactory; - -public final class DefaultJedisClientConfig implements JedisClientConfig { - - private final int connectionTimeoutMillis; - private final int socketTimeoutMillis; - private final int blockingSocketTimeoutMillis; - - private final String user; - private volatile String password; - private final int database; - private final String clientName; - - private final boolean ssl; - private final SSLSocketFactory sslSocketFactory; - private final SSLParameters sslParameters; - private final HostnameVerifier hostnameVerifier; - - private final HostAndPortMapper hostAndPortMapper; - - private DefaultJedisClientConfig(int connectionTimeoutMillis, int soTimeoutMillis, - int blockingSocketTimeoutMillis, String user, String password, int database, String clientName, - boolean ssl, SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier, HostAndPortMapper hostAndPortMapper) { - this.connectionTimeoutMillis = connectionTimeoutMillis; - this.socketTimeoutMillis = soTimeoutMillis; - this.blockingSocketTimeoutMillis = blockingSocketTimeoutMillis; - this.user = user; - this.password = password; - this.database = database; - this.clientName = clientName; - this.ssl = ssl; - this.sslSocketFactory = sslSocketFactory; - this.sslParameters = sslParameters; - this.hostnameVerifier = hostnameVerifier; - this.hostAndPortMapper = hostAndPortMapper; - } - - @Override - public int getConnectionTimeoutMillis() { - return connectionTimeoutMillis; - } - - @Override - public int getSocketTimeoutMillis() { - return socketTimeoutMillis; - } - - @Override - public int getBlockingSocketTimeoutMillis() { - return blockingSocketTimeoutMillis; - } - - @Override - public String getUser() { - return user; - } - - @Override - public String getPassword() { - return password; - } - - @Override - public synchronized void updatePassword(String password) { - if (!Objects.equals(this.password, password)) { - this.password = password; - } - } - - @Override - public int getDatabase() { - return database; - } - - @Override - public String getClientName() { - return clientName; - } - - @Override - public boolean isSsl() { - return ssl; - } - - @Override - public SSLSocketFactory getSslSocketFactory() { - return sslSocketFactory; - } - - @Override - public SSLParameters getSslParameters() { - return sslParameters; - } - - @Override - public HostnameVerifier getHostnameVerifier() { - return hostnameVerifier; - } - - @Override - public HostAndPortMapper getHostAndPortMapper() { - return hostAndPortMapper; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - - private int connectionTimeoutMillis = Protocol.DEFAULT_TIMEOUT; - private int socketTimeoutMillis = Protocol.DEFAULT_TIMEOUT; - private int blockingSocketTimeoutMillis = 0; - - private String user = null; - private String password = null; - private int database = Protocol.DEFAULT_DATABASE; - private String clientName = null; - - private boolean ssl = false; - private SSLSocketFactory sslSocketFactory = null; - private SSLParameters sslParameters = null; - private HostnameVerifier hostnameVerifier = null; - - private HostAndPortMapper hostAndPortMapper = null; - - private Builder() { - } - - public DefaultJedisClientConfig build() { - return new DefaultJedisClientConfig(connectionTimeoutMillis, socketTimeoutMillis, - blockingSocketTimeoutMillis, user, password, database, clientName, ssl, sslSocketFactory, - sslParameters, hostnameVerifier, hostAndPortMapper); - } - - public Builder connectionTimeoutMillis(int connectionTimeoutMillis) { - this.connectionTimeoutMillis = connectionTimeoutMillis; - return this; - } - - public Builder socketTimeoutMillis(int socketTimeoutMillis) { - this.socketTimeoutMillis = socketTimeoutMillis; - return this; - } - - public Builder blockingSocketTimeoutMillis(int blockingSocketTimeoutMillis) { - this.blockingSocketTimeoutMillis = blockingSocketTimeoutMillis; - return this; - } - - public Builder user(String user) { - this.user = user; - return this; - } - - public Builder password(String password) { - this.password = password; - return this; - } - - public Builder database(int database) { - this.database = database; - return this; - } - - public Builder clientName(String clientName) { - this.clientName = clientName; - return this; - } - - public Builder ssl(boolean ssl) { - this.ssl = ssl; - return this; - } - - public Builder sslSocketFactory(SSLSocketFactory sslSocketFactory) { - this.sslSocketFactory = sslSocketFactory; - return this; - } - - public Builder sslParameters(SSLParameters sslParameters) { - this.sslParameters = sslParameters; - return this; - } - - public Builder hostnameVerifier(HostnameVerifier hostnameVerifier) { - this.hostnameVerifier = hostnameVerifier; - return this; - } - - public Builder hostAndPortMapper(HostAndPortMapper hostAndPortMapper) { - this.hostAndPortMapper = hostAndPortMapper; - return this; - } - } - - public static DefaultJedisClientConfig copyConfig(JedisClientConfig copy) { - return new DefaultJedisClientConfig(copy.getConnectionTimeoutMillis(), - copy.getSocketTimeoutMillis(), copy.getBlockingSocketTimeoutMillis(), copy.getUser(), - copy.getPassword(), copy.getDatabase(), copy.getClientName(), copy.isSsl(), - copy.getSslSocketFactory(), copy.getSslParameters(), copy.getHostnameVerifier(), - copy.getHostAndPortMapper()); - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/DefaultJedisSocketFactory.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/DefaultJedisSocketFactory.java deleted file mode 100644 index ba654789c..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/DefaultJedisSocketFactory.java +++ /dev/null @@ -1,228 +0,0 @@ -package com.fr.third.redis.clients.jedis; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLParameters; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; - -import com.fr.third.redis.clients.jedis.exceptions.JedisConnectionException; -import com.fr.third.redis.clients.jedis.util.IOUtils; - -public class DefaultJedisSocketFactory implements JedisSocketFactory { - - protected static final HostAndPort DEFAULT_HOST_AND_PORT = new HostAndPort(Protocol.DEFAULT_HOST, - Protocol.DEFAULT_PORT); - - private volatile HostAndPort hostAndPort = DEFAULT_HOST_AND_PORT; - private int connectionTimeout = Protocol.DEFAULT_TIMEOUT; - private int socketTimeout = Protocol.DEFAULT_TIMEOUT; - private boolean ssl = false; - private SSLSocketFactory sslSocketFactory = null; - private SSLParameters sslParameters = null; - private HostnameVerifier hostnameVerifier = null; - private HostAndPortMapper hostAndPortMapper = null; - - public DefaultJedisSocketFactory() { - } - - public DefaultJedisSocketFactory(HostAndPort hostAndPort) { - this(hostAndPort, null); - } - - public DefaultJedisSocketFactory(JedisClientConfig config) { - this(null, config); - } - - @Deprecated - public DefaultJedisSocketFactory(String host, int port, int connectionTimeout, int socketTimeout, - boolean ssl, SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier) { - this.hostAndPort = new HostAndPort(host, port); - this.connectionTimeout = connectionTimeout; - this.socketTimeout = socketTimeout; - this.ssl = ssl; - this.sslSocketFactory = sslSocketFactory; - this.sslParameters = sslParameters; - this.hostnameVerifier = hostnameVerifier; - } - - public DefaultJedisSocketFactory(HostAndPort hostAndPort, JedisClientConfig config) { - if (hostAndPort != null) { - this.hostAndPort = hostAndPort; - } - if (config != null) { - this.connectionTimeout = config.getConnectionTimeoutMillis(); - this.socketTimeout = config.getSocketTimeoutMillis(); - this.ssl = config.isSsl(); - this.sslSocketFactory = config.getSslSocketFactory(); - this.sslParameters = config.getSslParameters(); - this.hostnameVerifier = config.getHostnameVerifier(); - this.hostAndPortMapper = config.getHostAndPortMapper(); - } - } - - @Override - 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()); - - if (ssl) { - SSLSocketFactory sslSocketFactory = getSslSocketFactory(); - if (null == sslSocketFactory) { - sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); - } - 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())) { - String message = String.format( - "The connection to '%s' failed ssl/tls hostname verification.", hostAndPort.getHost()); - throw new JedisConnectionException(message); - } - } - - return socket; - - } catch (IOException ex) { - - IOUtils.closeQuietly(socket); - - throw new JedisConnectionException("Failed to create socket.", ex); - } - } - - @Override - public void updateHostAndPort(HostAndPort hostAndPort) { - this.hostAndPort = hostAndPort; - } - - public HostAndPort getSocketHostAndPort() { - HostAndPortMapper mapper = getHostAndPortMapper(); - HostAndPort hostAndPort = getHostAndPort(); - if (mapper != null) { - HostAndPort mapped = mapper.getHostAndPort(hostAndPort); - if (mapped != null) { - return mapped; - } - } - return hostAndPort; - } - - public HostAndPort getHostAndPort() { - return this.hostAndPort; - } - - public void setHostAndPort(HostAndPort hostAndPort) { - this.hostAndPort = hostAndPort; - } - - @Override - public String getDescription() { - return this.hostAndPort.toString(); - } - - @Override - public String getHost() { - return this.hostAndPort.getHost(); - } - - @Override - public void setHost(String host) { - this.hostAndPort = new HostAndPort(host, this.hostAndPort.getPort()); - } - - @Override - public int getPort() { - return this.hostAndPort.getPort(); - } - - @Override - public void setPort(int port) { - this.hostAndPort = new HostAndPort(this.hostAndPort.getHost(), port); - } - - @Override - public int getConnectionTimeout() { - return this.connectionTimeout; - } - - @Override - public void setConnectionTimeout(int connectionTimeout) { - this.connectionTimeout = connectionTimeout; - } - - @Override - public int getSoTimeout() { - return this.socketTimeout; - } - - @Override - public void setSoTimeout(int soTimeout) { - this.socketTimeout = soTimeout; - } - - public boolean isSsl() { - return ssl; - } - - public void setSsl(boolean ssl) { - this.ssl = ssl; - } - - public SSLSocketFactory getSslSocketFactory() { - return sslSocketFactory; - } - - public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) { - this.sslSocketFactory = sslSocketFactory; - } - - public SSLParameters getSslParameters() { - return sslParameters; - } - - public void setSslParameters(SSLParameters sslParameters) { - this.sslParameters = sslParameters; - } - - public HostnameVerifier getHostnameVerifier() { - return hostnameVerifier; - } - - public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { - this.hostnameVerifier = hostnameVerifier; - } - - public HostAndPortMapper getHostAndPortMapper() { - return hostAndPortMapper; - } - - public void setHostAndPortMapper(HostAndPortMapper hostAndPortMapper) { - this.hostAndPortMapper = hostAndPortMapper; - } - - @Override - public String toString() { - return "DefaultJedisSocketFactory{" + hostAndPort.toString() + "}"; - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/GeoCoordinate.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/GeoCoordinate.java index 806c7e072..473cf064e 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/GeoCoordinate.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/GeoCoordinate.java @@ -19,8 +19,7 @@ public class GeoCoordinate { @Override public boolean equals(Object o) { - if (o == null) return false; - if (o == this) return true; + if (this == o) return true; if (!(o instanceof GeoCoordinate)) return false; GeoCoordinate that = (GeoCoordinate) o; diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/GeoRadiusResponse.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/GeoRadiusResponse.java index e33aadc7f..256ba660a 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/GeoRadiusResponse.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/GeoRadiusResponse.java @@ -6,7 +6,6 @@ public class GeoRadiusResponse { private byte[] member; private double distance; private GeoCoordinate coordinate; - private long rawScore; public GeoRadiusResponse(byte[] member) { this.member = member; @@ -35,12 +34,4 @@ public class GeoRadiusResponse { public GeoCoordinate getCoordinate() { return coordinate; } - - public long getRawScore() { - return rawScore; - } - - public void setRawScore(long rawScore) { - this.rawScore = rawScore; - } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/HostAndPort.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/HostAndPort.java index 66c6419c8..6dcfcb7d8 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/HostAndPort.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/HostAndPort.java @@ -10,7 +10,8 @@ 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; + public static String localhost; + private String host; private int port; @@ -30,15 +31,16 @@ public class HostAndPort implements Serializable { @Override public boolean equals(Object obj) { - if (obj == null) return false; - if (obj == this) return true; - if (!(obj instanceof HostAndPort)) return false; + if (obj instanceof HostAndPort) { + HostAndPort hp = (HostAndPort) obj; + + String thisHost = convertHost(host); + String hpHost = convertHost(hp.host); + return port == hp.port && thisHost.equals(hpHost); - HostAndPort hp = (HostAndPort) obj; + } - String thisHost = convertHost(host); - String hpHost = convertHost(hp.host); - return port == hp.port && thisHost.equals(hpHost); + return false; } @Override @@ -51,28 +53,16 @@ public class HostAndPort implements Serializable { return host + ":" + port; } - /** - * Creates HostAndPort with unconverted host. - * @param string String to parse. Must be in "host:port" format. Port is mandatory. - * @return parsed HostAndPort - */ - public static HostAndPort from(String string) { - int lastColon = string.lastIndexOf(":"); - String host = string.substring(0, lastColon); - 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; + */ + 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 }; } @@ -84,8 +74,8 @@ public class HostAndPort implements Serializable { * @see #convertHost(String) * @param from String to parse * @return HostAndPort instance - */ - public static HostAndPort parseString(String from) { + */ + 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. @@ -102,7 +92,7 @@ public class HostAndPort implements Serializable { 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. @@ -112,19 +102,19 @@ public class HostAndPort implements Serializable { * 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")) { + if (inetAddress.isLoopbackAddress() || host.equals("0.0.0.0") || host.startsWith("169.254")) return getLocalhost(); - } + else + return host; } catch (Exception e) { // Not a valid IP address - log.warn("{}.convertHost '{}' is not a valid IP address. ", HostAndPort.class.getName(), - host, e); + log.warn("{}.convertHost '" + host + "' is not a valid IP address. ", HostAndPort.class.getName(), e); + return host; } - return host; } public static void setLocalhost(String localhost) { @@ -135,6 +125,7 @@ public class HostAndPort implements Serializable { /** * This method resolves the localhost in a 'lazy manner'. + * * @return localhost */ public static String getLocalhost() { diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/HostAndPortMapper.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/HostAndPortMapper.java deleted file mode 100644 index b9db22c42..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/HostAndPortMapper.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.fr.third.redis.clients.jedis; - -public interface HostAndPortMapper { - - HostAndPort getHostAndPort(HostAndPort hap); -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Jedis.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Jedis.java index b2b41676c..4caee44b7 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Jedis.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Jedis.java @@ -13,47 +13,38 @@ import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocketFactory; -import com.fr.third.redis.clients.jedis.args.*; -import com.fr.third.redis.clients.jedis.commands.*; -import com.fr.third.redis.clients.jedis.params.*; -import com.fr.third.redis.clients.jedis.resps.*; +import com.fr.third.redis.clients.jedis.commands.AdvancedJedisCommands; +import com.fr.third.redis.clients.jedis.commands.BasicCommands; +import com.fr.third.redis.clients.jedis.commands.ClusterCommands; +import com.fr.third.redis.clients.jedis.commands.JedisCommands; +import com.fr.third.redis.clients.jedis.commands.ModuleCommands; +import com.fr.third.redis.clients.jedis.commands.MultiKeyCommands; +import com.fr.third.redis.clients.jedis.commands.ScriptingCommands; +import com.fr.third.redis.clients.jedis.commands.SentinelCommands; +import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; +import com.fr.third.redis.clients.jedis.params.SetParams; +import com.fr.third.redis.clients.jedis.params.ZAddParams; +import com.fr.third.redis.clients.jedis.params.ZIncrByParams; import com.fr.third.redis.clients.jedis.util.SafeEncoder; import com.fr.third.redis.clients.jedis.util.Slowlog; public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands, - AdvancedJedisCommands, ScriptingCommands, BasicCommands, ClusterCommands, SentinelCommands, - ModuleCommands { + AdvancedJedisCommands, ScriptingCommands, BasicCommands, ClusterCommands, SentinelCommands, ModuleCommands { - /** - * @deprecated This will be private in future. - */ - @Deprecated protected JedisPoolAbstract dataSource = null; public Jedis() { super(); } - /** - * @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 - */ - @Deprecated - public Jedis(final String uri) { - super(uri); + public Jedis(final String host) { + super(host); } public Jedis(final HostAndPort hp) { super(hp); } - public Jedis(final HostAndPort hp, final JedisClientConfig config) { - super(hp, config); - } - public Jedis(final String host, final int port) { super(host, port); } @@ -86,30 +77,18 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand super(host, port, connectionTimeout, soTimeout); } - 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, final boolean ssl) { super(host, port, connectionTimeout, soTimeout, ssl); } 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) { + 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 int infiniteSoTimeout, final boolean ssl, final SSLSocketFactory sslSocketFactory, - final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - super(host, port, connectionTimeout, soTimeout, infiniteSoTimeout, ssl, sslSocketFactory, - sslParameters, hostnameVerifier); - } - public Jedis(JedisShardInfo shardInfo) { super(shardInfo); } @@ -142,62 +121,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand super(uri, connectionTimeout, soTimeout, sslSocketFactory, sslParameters, hostnameVerifier); } - 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); - } - - public Jedis(final URI uri, JedisClientConfig config) { - super(uri, config); - } - - /** - * @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); - } - - public Jedis(final JedisSocketFactory jedisSocketFactory, final JedisClientConfig clientConfig) { - super(jedisSocketFactory, clientConfig); - } - - /** - * 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(); - client.copy(srcKey, dstKey, db, replace); - return BuilderFactory.BOOLEAN.build(client.getIntegerReply()); - } - - /** - * 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(); - client.copy(srcKey, dstKey, replace); - return BuilderFactory.BOOLEAN.build(client.getIntegerReply()); - } - /** * Works same as ping() but returns argument message instead of PONG. * @param message @@ -205,7 +128,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand */ public String ping(final String message) { checkIsInMultiOrPipeline(); - client.ping(message); + client.sendCommand(Protocol.Command.PING, message); return client.getBulkReply(); } @@ -242,9 +165,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } /** - * 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. + * Get the value of the specified key. If the key does not exist null 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 @@ -253,30 +175,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand @Override public String get(final String key) { checkIsInMultiOrPipeline(); - client.get(key); - return client.getBulkReply(); - } - - /** - * 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(); - client.getDel(key); - return client.getBulkReply(); - } - - @Override - public String getEx(String key, GetExParams params) { - checkIsInMultiOrPipeline(); - client.getEx(key, params); + client.sendCommand(Protocol.Command.GET, key); return client.getBulkReply(); } @@ -295,8 +194,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } /** - * 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 + * Test if the specified key exists. The command returns "1" if the key exists, otherwise "0" is + * returned. Note that even keys set with an empty string as value will return "1". Time * complexity: O(1) * @param key * @return Boolean reply, true if the key exists, otherwise false @@ -351,7 +250,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand @Override public Long unlink(final String key) { - checkIsInMultiOrPipeline(); client.unlink(key); return client.getIntegerReply(); } @@ -428,9 +326,9 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand * 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 + * Voltile 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 @@ -446,16 +344,16 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand * 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 String key, final int seconds) { checkIsInMultiOrPipeline(); client.expire(key, seconds); return client.getIntegerReply(); } /** - * 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 exctly 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 specifing 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 @@ -554,7 +452,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } /** - * Get the values of all the specified keys. If one or more keys don't exist or is not of type + * Get the values of all the specified keys. If one or more keys dont 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. *

      @@ -597,7 +495,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand * @return Status code reply */ @Override - public String setex(final String key, final long seconds, final String value) { + public String setex(final String key, final int seconds, final String value) { checkIsInMultiOrPipeline(); client.setex(key, seconds, value); return client.getStatusCodeReply(); @@ -743,7 +641,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand public Double incrByFloat(final String key, final double increment) { checkIsInMultiOrPipeline(); client.incrByFloat(key, increment); - return BuilderFactory.DOUBLE.build(client.getOne()); + String dval = client.getBulkReply(); + return (dval != null ? new Double(dval) : null); } /** @@ -948,14 +847,15 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand public Double hincrByFloat(final String key, final String field, final double value) { checkIsInMultiOrPipeline(); client.hincrByFloat(key, field, value); - return BuilderFactory.DOUBLE.build(client.getOne()); + final String dval = client.getBulkReply(); + return (dval != null ? new Double(dval) : null); } /** * 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 + * @return Return 1 if the hash stored at key contains the specified field. Return 0 if the key is * not found or the field is not present. */ @Override @@ -1021,7 +921,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand public List hvals(final String key) { checkIsInMultiOrPipeline(); client.hvals(key); - return client.getMultiBulkReply(); + final List lresult = client.getMultiBulkReply(); + return lresult; } /** @@ -1038,50 +939,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand return BuilderFactory.STRING_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 String hrandfield(final String key) { - checkIsInMultiOrPipeline(); - client.hrandfield(key); - return client.getStatusCodeReply(); - } - - /** - * 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(); - client.hrandfield(key, count); - return client.getMultiBulkReply(); - } - - /** - * 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(); - client.hrandfieldWithValues(key, count); - return BuilderFactory.STRING_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 @@ -1263,7 +1120,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand * 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 + * as value to remove against the list (a,b,c,hello,x,hello,hello) will lave 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. @@ -1298,35 +1155,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand return client.getBulkReply(); } - @Override - public List lpop(final String key, final int count) { - checkIsInMultiOrPipeline(); - client.lpop(key, count); - return client.getMultiBulkReply(); - } - - @Override - public Long lpos(final String key, final String element) { - checkIsInMultiOrPipeline(); - client.lpos(key, element); - return client.getIntegerReply(); - } - - @Override - public Long lpos(final String key, final String element, final LPosParams params) { - checkIsInMultiOrPipeline(); - client.lpos(key, element, params); - return client.getIntegerReply(); - } - - @Override - public List lpos(final String key, final String 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" RPOP will return "c" and the list will become @@ -1344,13 +1172,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand return client.getBulkReply(); } - @Override - public List rpop(final String key, final int count) { - checkIsInMultiOrPipeline(); - client.rpop(key, count); - return client.getMultiBulkReply(); - } - /** * 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 @@ -1359,7 +1180,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand *

      * 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. + * from the list and pusing it as first element of the list, so it's a "list rotation" command. *

      * Time complexity: O(1) * @param srckey @@ -1447,12 +1268,11 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand checkIsInMultiOrPipeline(); client.spop(key, count); final List members = client.getMultiBulkReply(); - 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 + * Move the specifided 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. *

      @@ -1492,13 +1312,13 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } /** - * Return true if member is a member of the set stored at key, otherwise false is returned. + * Return 1 if member is a member of the set stored at key, otherwise 0 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 + * @return Integer reply, specifically: 1 if the element is a member of the set 0 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) { @@ -1507,22 +1327,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand 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 String key, final String... 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(String, long, long) LRANGE} the result is sent to the @@ -1547,8 +1351,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } /** - * This command works exactly like {@link #sinter(String...) SINTER} but instead of being returned - * the resulting set is stored as dstkey. + * This commnad works exactly like {@link #sinter(String...) SINTER} but instead of being returned + * the resulting set is sotred as dstkey. *

      * Time complexity O(N*M) worst case where N is the cardinality of the smallest set and M the * number of sets @@ -1603,14 +1407,14 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand * 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: @@ -1658,19 +1462,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand return client.getBulkReply(); } - /** - * 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(); @@ -1679,10 +1470,10 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } /** - * Add the specified member having the specified score to the sorted set stored at key. If member + * Add the specified member having the specifeid 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 + * member as sole member is crated. 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. @@ -1723,34 +1514,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand 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()); - } - - @Override - public Set zdiff(String... keys) { - checkIsInMultiOrPipeline(); - client.zdiff(keys); - return SetFromList.of(client.getMultiBulkReply()); - } - - @Override - public Set zdiffWithScores(String... keys) { - checkIsInMultiOrPipeline(); - client.zdiffWithScores(keys); - return getTupledSet(); - } - - @Override - public Long zdiffStore(final String dstkey, final String... keys) { - checkIsInMultiOrPipeline(); - client.zdiffStore(dstkey, keys); - return BuilderFactory.LONG.build(client.getOne()); - } - @Override public Set zrange(final String key, final long start, final long stop) { checkIsInMultiOrPipeline(); @@ -1782,7 +1545,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand * 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. + * member is crated. 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. @@ -1803,8 +1566,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } @Override - public Double zincrby(final String key, final double increment, final String member, - final ZIncrByParams params) { + public Double zincrby(final String key, final double increment, final String member, final ZIncrByParams params) { checkIsInMultiOrPipeline(); client.zincrby(key, increment, member, params); return BuilderFactory.DOUBLE.build(client.getOne()); @@ -1878,28 +1640,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand return getTupledSet(); } - @Override - public String zrandmember(final String key) { - checkIsInMultiOrPipeline(); - client.zrandmember(key); - return client.getBulkReply(); - } - - @Override - public Set zrandmember(final String key, final long count) { - checkIsInMultiOrPipeline(); - client.zrandmember(key, count); - final List members = client.getMultiBulkReply(); - return members == null ? null : SetFromList.of(members); - } - - @Override - public Set zrandmemberWithScores(final String 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. @@ -1932,53 +1672,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand 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 String key, final String... members) { - checkIsInMultiOrPipeline(); - client.zmscore(key, members); - return BuilderFactory.DOUBLE_LIST.build(client.getBinaryMultiBulkReply()); - } - - @Override - public Tuple zpopmax(final String key) { - checkIsInMultiOrPipeline(); - client.zpopmax(key); - return BuilderFactory.TUPLE.build(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zpopmax(final String key, final int count) { - checkIsInMultiOrPipeline(); - client.zpopmax(key, count); - return getTupledSet(); - } - - @Override - public Tuple zpopmin(final String key) { - checkIsInMultiOrPipeline(); - client.zpopmin(key); - return BuilderFactory.TUPLE.build(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zpopmin(final String key, final int count) { - checkIsInMultiOrPipeline(); - client.zpopmin(key, count); - return getTupledSet(); - } - @Override public String watch(final String... keys) { - checkIsInMultiOrPipeline(); client.watch(keys); return client.getStatusCodeReply(); } @@ -2009,65 +1704,65 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand * 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]
          * 
      @@ -2084,64 +1779,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand return client.getMultiBulkReply(); } - /** - * 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(); - 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(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(); - client.sort(key, dstkey); - return client.getIntegerReply(); - } - - @Override - public String lmove(final String srcKey, final String dstKey, final ListDirection from, - final ListDirection to) { - checkIsInMultiOrPipeline(); - client.lmove(srcKey, dstKey, from, to); - return client.getBulkReply(); - } - - @Override - public String blmove(final String srcKey, final String dstKey, final ListDirection from, - final ListDirection to, final double timeout) { - checkIsInMultiOrPipeline(); - client.blmove(srcKey, dstKey, from, to, timeout); - client.setTimeoutInfinite(); - try { - return client.getBulkReply(); - } 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 @@ -2206,22 +1843,82 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand */ @Override public List blpop(final int timeout, final String... keys) { - return blpop(getKeysAndTimeout(timeout, keys)); + return blpop(getArgsAddTimeout(timeout, keys)); + } + + private String[] getArgsAddTimeout(int timeout, String[] keys) { + final int keyCount = keys.length; + final String[] args = new String[keyCount + 1]; + for (int at = 0; at != keyCount; ++at) { + args[at] = keys[at]; + } + + args[keyCount] = String.valueOf(timeout); + return args; } @Override - public KeyedListElement blpop(final double timeout, final String... keys) { + public List blpop(final String... args) { checkIsInMultiOrPipeline(); - client.blpop(timeout, keys); + client.blpop(args); client.setTimeoutInfinite(); try { - return BuilderFactory.KEYED_LIST_ELEMENT.build(client.getBinaryMultiBulkReply()); + return client.getMultiBulkReply(); } finally { client.rollbackTimeout(); } } - /** + @Override + public List brpop(final String... args) { + checkIsInMultiOrPipeline(); + client.brpop(args); + client.setTimeoutInfinite(); + try { + return client.getMultiBulkReply(); + } finally { + client.rollbackTimeout(); + } + } + + /** + * 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(); + 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(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(); + client.sort(key, dstkey); + return client.getIntegerReply(); + } + + /** * 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. @@ -2285,97 +1982,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand */ @Override public List brpop(final int timeout, final String... keys) { - return brpop(getKeysAndTimeout(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; - } - - @Override - public List blpop(final String... args) { - checkIsInMultiOrPipeline(); - client.blpop(args); - client.setTimeoutInfinite(); - try { - return client.getMultiBulkReply(); - } finally { - client.rollbackTimeout(); - } - } - - @Override - public List brpop(final String... args) { - checkIsInMultiOrPipeline(); - client.brpop(args); - client.setTimeoutInfinite(); - try { - return client.getMultiBulkReply(); - } finally { - client.rollbackTimeout(); - } - } - - @Override - public KeyedZSetElement bzpopmax(double timeout, String... keys) { - checkIsInMultiOrPipeline(); - client.bzpopmax(timeout, keys); - client.setTimeoutInfinite(); - try { - return BuilderFactory.KEYED_ZSET_ELEMENT.build(client.getBinaryMultiBulkReply()); - } finally { - client.rollbackTimeout(); - } - } - - @Override - public KeyedZSetElement bzpopmin(double timeout, String... keys) { - checkIsInMultiOrPipeline(); - client.bzpopmin(timeout, keys); - client.setTimeoutInfinite(); - try { - return BuilderFactory.KEYED_ZSET_ELEMENT.build(client.getBinaryMultiBulkReply()); - } finally { - client.rollbackTimeout(); - } - } - - @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}); - } - - @Override - public List brpop(final int timeout, final String key) { - return brpop(key, String.valueOf(timeout)); - } - - @Override - public KeyedListElement brpop(double timeout, String key) { - return brpop(timeout, new String[]{key}); + return brpop(getArgsAddTimeout(timeout, keys)); } @Override @@ -2501,8 +2108,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand * @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 @@ -2629,8 +2234,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand * @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 @@ -2722,10 +2325,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand *

      * 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) { @@ -2761,34 +2360,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand 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 - * @return - */ - @Override - public Set zunion(ZParams params, String... keys) { - checkIsInMultiOrPipeline(); - client.zunion(params, keys); - return BuilderFactory.STRING_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 - * @return - */ - @Override - public Set zunionWithScores(ZParams params, String... keys) { - checkIsInMultiOrPipeline(); - client.zunionWithScores(params, keys); - return getTupledSet(); - } - /** * 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 @@ -2864,34 +2435,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand 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 - * @return - */ - @Override - public Set zinter(final ZParams params, final String... keys) { - checkIsInMultiOrPipeline(); - client.zinter(params, keys); - return BuilderFactory.STRING_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 - * @return - */ - @Override - public Set zinterWithScores(final ZParams params, final String... keys) { - checkIsInMultiOrPipeline(); - client.zinterWithScores(params, keys); - return getTupledSet(); - } - /** * 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 @@ -3000,8 +2543,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } @Override - public Set zrevrangeByLex(final String key, final String max, final String min, - final int offset, final int count) { + public Set 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(); @@ -3039,7 +2581,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand */ @Override public Long persist(final String key) { - checkIsInMultiOrPipeline(); client.persist(key); return client.getIntegerReply(); } @@ -3075,7 +2616,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand */ @Override public String brpoplpush(final String source, final String destination, final int timeout) { - checkIsInMultiOrPipeline(); client.brpoplpush(source, destination, timeout); client.setTimeoutInfinite(); try { @@ -3154,7 +2694,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand * are reported as a list of key-value pairs. *

      * Example: - * + * *

          * $ redis-cli config get '*'
          * 1. "dbfilename"
      @@ -3169,7 +2709,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
          * 10. "everysec"
          * 11. "save"
          * 12. "3600 1 300 100 60 10000"
      -   *
      +   * 
          * $ redis-cli config get 'm*'
          * 1. "masterauth"
          * 2. (nil)
      @@ -3181,7 +2721,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
          */
         @Override
         public List configGet(final String pattern) {
      -    checkIsInMultiOrPipeline();
           client.configGet(pattern);
           return client.getMultiBulkReply();
         }
      @@ -3202,12 +2741,12 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
          * 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. + *
      • The save paramter 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. *
      @@ -3217,11 +2756,21 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand */ @Override public String configSet(final String parameter, final String value) { - checkIsInMultiOrPipeline(); client.configSet(parameter, value); return client.getStatusCodeReply(); } + @Override + public Object eval(final String script, final int keyCount, final String... params) { + client.setTimeoutInfinite(); + try { + client.eval(script, keyCount, params); + return getEvalResult(); + } finally { + client.rollbackTimeout(); + } + } + @Override public void subscribe(final JedisPubSub jedisPubSub, final String... channels) { client.setTimeoutInfinite(); @@ -3235,6 +2784,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand @Override public Long publish(final String channel, final String message) { checkIsInMultiOrPipeline(); + connect(); client.publish(channel, message); return client.getIntegerReply(); } @@ -3265,18 +2815,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand return params; } - @Override - public Object eval(final String script, final int keyCount, final String... params) { - checkIsInMultiOrPipeline(); - client.eval(script, keyCount, params); - client.setTimeoutInfinite(); - try { - return SafeEncoder.encodeObject(client.getOne()); - } finally { - client.rollbackTimeout(); - } - } - @Override public Object eval(final String script, final List keys, final List args) { return eval(script, keys.size(), getParams(keys, args)); @@ -3292,6 +2830,26 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand return evalsha(sha1, 0); } + private Object getEvalResult() { + return evalResult(client.getOne()); + } + + private Object evalResult(Object result) { + if (result instanceof byte[]) return SafeEncoder.encode((byte[]) result); + + if (result instanceof List) { + List list = (List) result; + List listResult = new ArrayList(list.size()); + for (Object bin : list) { + listResult.add(evalResult(bin)); + } + + return listResult; + } + + return result; + } + @Override public Object evalsha(final String sha1, final List keys, final List args) { return evalsha(sha1, keys.size(), getParams(keys, args)); @@ -3301,7 +2859,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand public Object evalsha(final String sha1, final int keyCount, final String... params) { checkIsInMultiOrPipeline(); client.evalsha(sha1, keyCount, params); - return SafeEncoder.encodeObject(client.getOne()); + return getEvalResult(); } @Override @@ -3315,7 +2873,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand public List scriptExists(final String... sha1) { client.scriptExists(sha1); List result = client.getIntegerMultiBulkReply(); - List exists = new ArrayList<>(); + List exists = new ArrayList(); for (Long value : result) exists.add(value == 1); @@ -3359,18 +2917,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand return client.getIntegerReply(); } - @Override - public List objectHelp() { - client.objectHelp(); - return client.getMultiBulkReply(); - } - - @Override - public Long objectFreq(final String key) { - client.objectFreq(key); - return client.getIntegerReply(); - } - @Override public Long bitcount(final String key) { checkIsInMultiOrPipeline(); @@ -3419,7 +2965,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand * 22) "2" * 23) "quorum" * 24) "2" - * + * * * @return */ @@ -3429,9 +2975,9 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand client.sentinel(Protocol.SENTINEL_MASTERS); final List reply = client.getObjectMultiBulkReply(); - final List> masters = new ArrayList<>(); + final List> masters = new ArrayList>(); for (Object obj : reply) { - masters.add(BuilderFactory.STRING_MAP.build(obj)); + masters.add(BuilderFactory.STRING_MAP.build((List) obj)); } return masters; } @@ -3502,13 +3048,14 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand * @return */ @Override + @SuppressWarnings("rawtypes") public List> sentinelSlaves(final String masterName) { client.sentinel(Protocol.SENTINEL_SLAVES, masterName); final List reply = client.getObjectMultiBulkReply(); - final List> slaves = new ArrayList<>(); + final List> slaves = new ArrayList>(); for (Object obj : reply) { - slaves.add(BuilderFactory.STRING_MAP.build(obj)); + slaves.add(BuilderFactory.STRING_MAP.build((List) obj)); } return slaves; } @@ -3520,8 +3067,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } @Override - public String sentinelMonitor(final String masterName, final String ip, final int port, - final int quorum) { + 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(); @@ -3558,27 +3104,12 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } @Override - public String restore(final String key, final long ttl, final byte[] serializedValue) { + public String restore(final String key, final int ttl, final byte[] serializedValue) { checkIsInMultiOrPipeline(); client.restore(key, ttl, serializedValue); return client.getStatusCodeReply(); } - @Override - public String restoreReplace(final String key, final long ttl, final byte[] serializedValue) { - checkIsInMultiOrPipeline(); - client.restoreReplace(key, ttl, serializedValue); - return client.getStatusCodeReply(); - } - - @Override - public String restore(final String key, final long ttl, final byte[] serializedValue, - final RestoreParams params) { - checkIsInMultiOrPipeline(); - client.restore(key, ttl, serializedValue, params); - return client.getStatusCodeReply(); - } - @Override public Long pexpire(final String key, final long milliseconds) { checkIsInMultiOrPipeline(); @@ -3616,124 +3147,64 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand return client.getStatusCodeReply(); } - @Override - public String clientKill(final String ipPort) { + public String clientKill(final String client) { checkIsInMultiOrPipeline(); - this.client.clientKill(ipPort); + this.client.clientKill(client); return this.client.getStatusCodeReply(); } - @Override - public String clientGetname() { + public String clientSetname(final String name) { checkIsInMultiOrPipeline(); - client.clientGetname(); - return client.getBulkReply(); + client.clientSetname(name); + return client.getStatusCodeReply(); } - @Override - public String clientList() { + public String migrate(final String host, final int port, final String key, + final int destinationDb, final int timeout) { checkIsInMultiOrPipeline(); - client.clientList(); - return client.getBulkReply(); + client.migrate(host, port, key, destinationDb, timeout); + return client.getStatusCodeReply(); } @Override - public String clientList(final long... clientIds) { - checkIsInMultiOrPipeline(); - client.clientList(clientIds); - return client.getBulkReply(); + public ScanResult scan(final String cursor) { + return scan(cursor, new ScanParams()); } @Override - public String clientInfo() { + public ScanResult scan(final String cursor, final ScanParams params) { checkIsInMultiOrPipeline(); - client.clientInfo(); - return client.getBulkReply(); + client.scan(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); } @Override - public String clientSetname(final String name) { - checkIsInMultiOrPipeline(); - client.clientSetname(name); - return client.getStatusCodeReply(); + public ScanResult> hscan(final String key, final String cursor) { + return hscan(key, cursor, new ScanParams()); } @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 - * @return - */ - @Override - public Long clientUnblock(final long clientId, final UnblockType unblockType) { - checkIsInMultiOrPipeline(); - client.clientUnblock(clientId, unblockType); - return client.getIntegerReply(); - } - - @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(); - } - - @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(); - } - - @Override - public ScanResult scan(final String cursor) { - return scan(cursor, new ScanParams()); - } - - @Override - public ScanResult scan(final String cursor, final ScanParams params) { - checkIsInMultiOrPipeline(); - client.scan(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); - } - - @Override - public ScanResult> hscan(final String key, final String cursor) { - return hscan(key, cursor, new ScanParams()); - } - - @Override - public ScanResult> hscan(final String key, final String cursor, - final ScanParams params) { + 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> 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()), + results.add(new AbstractMap.SimpleEntry(SafeEncoder.encode(iterator.next()), SafeEncoder.encode(iterator.next()))); } - return new ScanResult<>(newcursor, results); + return new ScanResult>(newcursor, results); } @Override @@ -3747,12 +3218,12 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand client.sscan(key, cursor, params); List result = client.getObjectMultiBulkReply(); String newcursor = new String((byte[]) result.get(0)); - List results = new ArrayList<>(); + 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 new ScanResult(newcursor, results); } @Override @@ -3766,13 +3237,13 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand client.zscan(key, cursor, params); List result = client.getObjectMultiBulkReply(); String newcursor = new String((byte[]) result.get(0)); - List results = new ArrayList<>(); + 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 new ScanResult(newcursor, results); } @Override @@ -3784,7 +3255,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand @Override public String readonly() { - checkIsInMultiOrPipeline(); client.readonly(); return client.getStatusCodeReply(); } @@ -3949,15 +3419,13 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand @Override public void close() { if (dataSource != null) { - JedisPoolAbstract pool = this.dataSource; - this.dataSource = null; - if (isBroken()) { - pool.returnBrokenResource(this); + if (client.isBroken()) { + this.dataSource.returnBrokenResource(this); } else { - pool.returnResource(this); + this.dataSource.returnResource(this); } } else { - super.close(); + client.close(); } } @@ -3994,24 +3462,26 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } @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(); + public List blpop(final int timeout, final String key) { + return blpop(key, String.valueOf(timeout)); } @Override - public Long geoadd(final String key, final Map memberCoordinateMap) { + public List brpop(final int timeout, final String key) { + return brpop(key, String.valueOf(timeout)); + } + + @Override + public Long geoadd(final String key, final double longitude, final double latitude, final String member) { checkIsInMultiOrPipeline(); - client.geoadd(key, memberCoordinateMap); + client.geoadd(key, longitude, latitude, member); return client.getIntegerReply(); } @Override - public Long geoadd(final String key, final GeoAddParams params, final Map memberCoordinateMap) { + public Long geoadd(final String key, final Map memberCoordinateMap) { checkIsInMultiOrPipeline(); - client.geoadd(key, params, memberCoordinateMap); + client.geoadd(key, memberCoordinateMap); return client.getIntegerReply(); } @@ -4019,15 +3489,16 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand public Double geodist(final String key, final String member1, final String member2) { checkIsInMultiOrPipeline(); client.geodist(key, member1, member2); - return BuilderFactory.DOUBLE.build(client.getOne()); + String dval = client.getBulkReply(); + return (dval != null ? new Double(dval) : null); } @Override - public Double geodist(final String key, final String member1, final String member2, - final GeoUnit unit) { + 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()); + String dval = client.getBulkReply(); + return (dval != null ? new Double(dval) : null); } @Override @@ -4045,212 +3516,62 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } @Override - public List georadius(final String key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { + 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()); } @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()); - } - - @Override - public List georadius(final String key, final double longitude, - final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { + 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()); } @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(); - } - - @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()); - } - - @Override - public List georadiusByMember(final String key, final String member, - final double radius, final GeoUnit unit) { + 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()); } @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()); - } - - @Override - public List georadiusByMember(final String key, final String member, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { + 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()); } - @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(); - } - - @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()); - } - @Override public String moduleLoad(final String path) { - checkIsInMultiOrPipeline(); client.moduleLoad(path); return client.getStatusCodeReply(); } @Override public String moduleUnload(final String name) { - checkIsInMultiOrPipeline(); client.moduleUnload(name); return client.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(); - } - - @Override - public List bitfield(final String key, final String... arguments) { + public List bitfield(final String key, final String...arguments) { checkIsInMultiOrPipeline(); client.bitfield(key, arguments); return client.getIntegerMultiBulkReply(); } - @Override - public List bitfieldReadonly(final String key, final String... arguments) { - checkIsInMultiOrPipeline(); - client.bitfieldReadonly(key, arguments); - return client.getIntegerMultiBulkReply(); - } - @Override public Long hstrlen(final String key, final String field) { checkIsInMultiOrPipeline(); @@ -4258,315 +3579,4 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand return client.getIntegerReply(); } - @Override - public String memoryDoctor() { - checkIsInMultiOrPipeline(); - client.memoryDoctor(); - return client.getBulkReply(); - } - - @Override - public Long memoryUsage(final String key) { - checkIsInMultiOrPipeline(); - client.memoryUsage(key); - return client.getIntegerReply(); - } - - @Override - public Long memoryUsage(final String key, final int samples) { - checkIsInMultiOrPipeline(); - client.memoryUsage(key, samples); - return client.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); - } - - @Override - public StreamEntryID xadd(final String key, final Map hash, final XAddParams params) { - checkIsInMultiOrPipeline(); - client.xadd(key, hash, params); - return BuilderFactory.STREAM_ENTRY_ID.build(client.getBinaryBulkReply()); - } - - @Override - public Long xlen(final String key) { - checkIsInMultiOrPipeline(); - client.xlen(key); - return client.getIntegerReply(); - } - - @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()); - } - - /** - * {@inheritDoc} - */ - @Override - 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()); - } - - @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()); - } - - /** - * {@inheritDoc} - */ - @Override - 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(); - } - } - - @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(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public long xack(final String key, final String group, final StreamEntryID... ids) { - checkIsInMultiOrPipeline(); - client.xack(key, group, ids); - return client.getIntegerReply(); - } - - @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(); - } - - @Override - public String xgroupSetID(final String key, final String groupname, final StreamEntryID id) { - checkIsInMultiOrPipeline(); - client.xgroupSetID(key, groupname, id); - return client.getStatusCodeReply(); - } - - @Override - public long xgroupDestroy(final String key, final String groupname) { - checkIsInMultiOrPipeline(); - client.xgroupDestroy(key, groupname); - return client.getIntegerReply(); - } - - @Override - public Long xgroupDelConsumer(final String key, final String groupname, final String consumerName) { - checkIsInMultiOrPipeline(); - client.xgroupDelConsumer(key, groupname, consumerName); - return client.getIntegerReply(); - } - - @Override - public long xdel(final String key, final StreamEntryID... ids) { - checkIsInMultiOrPipeline(); - client.xdel(key, ids); - return client.getIntegerReply(); - } - - @Override - public long xtrim(final String key, final long maxLen, final boolean approximateLength) { - checkIsInMultiOrPipeline(); - client.xtrim(key, maxLen, approximateLength); - return client.getIntegerReply(); - } - - @Override - public long xtrim(final String key, final XTrimParams params) { - checkIsInMultiOrPipeline(); - client.xtrim(key, params); - return client.getIntegerReply(); - } - - /** - * {@inheritDoc} - */ - @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(); - } - } - - @Override - public List>> xreadGroup(final String groupname, - 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(); - } - } - - @Override - public StreamPendingSummary xpending(final String key, final String groupname) { - checkIsInMultiOrPipeline(); - client.xpending(key, groupname); - return BuilderFactory.STREAM_PENDING_SUMMARY.build(client.getObjectMultiBulkReply()); - } - - @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()); - } - - @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()); - } - - @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()); - } - - @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()); - } - - @Override - public StreamInfo xinfoStream(String key) { - client.xinfoStream(key); - - return BuilderFactory.STREAM_INFO.build(client.getObjectMultiBulkReply()); - - } - - @Override - public List xinfoGroup(String key) { - client.xinfoGroup(key); - - return BuilderFactory.STREAM_GROUP_INFO_LIST.build(client.getObjectMultiBulkReply()); - - } - - @Override - public List xinfoConsumers(String key, String group) { - client.xinfoConsumers(key, group); - - return BuilderFactory.STREAM_CONSUMERS_INFO_LIST.build(client.getObjectMultiBulkReply()); - - } - - public Object sendCommand(ProtocolCommand cmd, String... args) { - checkIsInMultiOrPipeline(); - client.sendCommand(cmd, args); - return client.getOne(); - } - - public Object sendBlockingCommand(ProtocolCommand cmd, String... args) { - checkIsInMultiOrPipeline(); - client.sendCommand(cmd, args); - client.setTimeoutInfinite(); - try { - return client.getOne(); - } finally { - client.rollbackTimeout(); - } - } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClientConfig.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClientConfig.java deleted file mode 100644 index c7196d9a0..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClientConfig.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.fr.third.redis.clients.jedis; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLParameters; -import javax.net.ssl.SSLSocketFactory; - -public interface JedisClientConfig { - - /** - * @return Connection timeout in milliseconds - */ - default int getConnectionTimeoutMillis() { - return Protocol.DEFAULT_TIMEOUT; - } - - /** - * @return Socket timeout in milliseconds - */ - default int getSocketTimeoutMillis() { - return Protocol.DEFAULT_TIMEOUT; - } - - /** - * @return Socket timeout (in milliseconds) to use during blocking operation. Default is '0', - * which means to block forever. - */ - default int getBlockingSocketTimeoutMillis() { - return 0; - } - - /** - * @return Redis ACL user - */ - default String getUser() { - return null; - } - - default String getPassword() { - return null; - } - - default void updatePassword(String password) { - } - - default int getDatabase() { - return Protocol.DEFAULT_DATABASE; - } - - default String getClientName() { - return null; - } - - /** - * @return true - to create a TLS connection. false - otherwise. - */ - default boolean isSsl() { - return false; - } - - default SSLSocketFactory getSslSocketFactory() { - return null; - } - - default SSLParameters getSslParameters() { - return null; - } - - default HostnameVerifier getHostnameVerifier() { - return null; - } - - default HostAndPortMapper getHostAndPortMapper() { - return null; - } - -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisCluster.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisCluster.java index 7f1b001bd..dd7de359d 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisCluster.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisCluster.java @@ -1,2982 +1,1989 @@ package com.fr.third.redis.clients.jedis; -import com.fr.third.redis.clients.jedis.args.*; +import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; +import com.fr.third.redis.clients.jedis.params.ZAddParams; +import com.fr.third.redis.clients.jedis.params.ZIncrByParams; import com.fr.third.redis.clients.jedis.commands.JedisClusterCommands; import com.fr.third.redis.clients.jedis.commands.JedisClusterScriptingCommands; import com.fr.third.redis.clients.jedis.commands.MultiKeyJedisClusterCommands; -import com.fr.third.redis.clients.jedis.commands.ProtocolCommand; -import com.fr.third.redis.clients.jedis.params.*; -import com.fr.third.redis.clients.jedis.resps.*; -import com.fr.third.redis.clients.jedis.util.JedisClusterHashTagUtil; import com.fr.third.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 javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLParameters; -import javax.net.ssl.SSLSocketFactory; import com.fr.third.org.apache.commons.pool2.impl.GenericObjectPoolConfig; -public class JedisCluster extends BinaryJedisCluster implements JedisClusterCommands, - MultiKeyJedisClusterCommands, JedisClusterScriptingCommands { - - public JedisCluster(HostAndPort node) { - this(Collections.singleton(node)); - } - - public JedisCluster(HostAndPort node, int timeout) { - this(Collections.singleton(node), timeout); - } - - public JedisCluster(HostAndPort node, int timeout, int maxAttempts) { - this(Collections.singleton(node), timeout, maxAttempts); - } - - public JedisCluster(HostAndPort node, final GenericObjectPoolConfig poolConfig) { - this(Collections.singleton(node), 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) { - this(Collections.singleton(node), timeout, maxAttempts, poolConfig); - } - - public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, - 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) { - 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) { - 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) { - 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, - boolean ssl) { - this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, password, - clientName, poolConfig, ssl); - } - - public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, - String user, String password, String clientName, - final GenericObjectPoolConfig poolConfig, boolean ssl) { - this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, user, password, - clientName, poolConfig, ssl); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, - String password, String clientName, final GenericObjectPoolConfig poolConfig, - boolean ssl, SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier, JedisClusterHostAndPortMap hostAndPortMap) { - this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, password, - clientName, poolConfig, ssl, sslSocketFactory, sslParameters, hostnameVerifier, - hostAndPortMap); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, - String user, String password, String clientName, - final GenericObjectPoolConfig poolConfig, boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier, JedisClusterHostAndPortMap hostAndPortMap) { - this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, user, password, - clientName, poolConfig, ssl, sslSocketFactory, sslParameters, hostnameVerifier, - hostAndPortMap); - } - - public JedisCluster(HostAndPort node, final JedisClientConfig clientConfig, int maxAttempts, - final GenericObjectPoolConfig poolConfig) { - this(Collections.singleton(node), clientConfig, maxAttempts, poolConfig); - } - - public JedisCluster(Set nodes) { - this(nodes, DEFAULT_TIMEOUT); - } - - public JedisCluster(Set nodes, int timeout) { - this(nodes, timeout, DEFAULT_MAX_ATTEMPTS); - } - - public JedisCluster(Set nodes, int timeout, int maxAttempts) { - this(nodes, timeout, maxAttempts, new GenericObjectPoolConfig()); - } - - public JedisCluster(Set nodes, final GenericObjectPoolConfig poolConfig) { - this(nodes, DEFAULT_TIMEOUT, DEFAULT_MAX_ATTEMPTS, poolConfig); - } - - public JedisCluster(Set nodes, int timeout, - 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); - } - - 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, 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 user, String password, String clientName, - final GenericObjectPoolConfig poolConfig) { - super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, user, 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 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 maxAttempts, String user, String password, String clientName, - final GenericObjectPoolConfig poolConfig, boolean ssl) { - super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, user, password, clientName, - poolConfig, ssl); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public JedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout, - int maxAttempts, String password, String clientName, - final GenericObjectPoolConfig poolConfig, boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier, JedisClusterHostAndPortMap hostAndPortMap) { - super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, clientName, - poolConfig, ssl, sslSocketFactory, sslParameters, hostnameVerifier, hostAndPortMap); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public JedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout, - int infiniteSoTimeout, int maxAttempts, String password, String clientName, - final GenericObjectPoolConfig poolConfig, boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier, JedisClusterHostAndPortMap hostAndPortMap) { - this(jedisClusterNode, connectionTimeout, soTimeout, infiniteSoTimeout, maxAttempts, null, - password, clientName, poolConfig, ssl, sslSocketFactory, sslParameters, hostnameVerifier, - hostAndPortMap); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public JedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout, - int maxAttempts, String user, String password, String clientName, - final GenericObjectPoolConfig poolConfig, boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier, JedisClusterHostAndPortMap hostAndPortMap) { - super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, user, password, clientName, - poolConfig, ssl, sslSocketFactory, sslParameters, hostnameVerifier, hostAndPortMap); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public JedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout, - int infiniteSoTimeout, int maxAttempts, String user, String password, String clientName, - final GenericObjectPoolConfig poolConfig, boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier, JedisClusterHostAndPortMap hostAndPortMap) { - super(jedisClusterNode, connectionTimeout, soTimeout, infiniteSoTimeout, maxAttempts, user, - password, clientName, poolConfig, ssl, sslSocketFactory, sslParameters, hostnameVerifier, - hostAndPortMap); - } - - /** - * @param maxTotalRetriesDuration After this amount of time we will do no more retries and report - * the operation as failed. - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public JedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout, - int infiniteSoTimeout, int maxAttempts, String user, String password, String clientName, - final GenericObjectPoolConfig poolConfig, boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier, JedisClusterHostAndPortMap hostAndPortMap, - Duration maxTotalRetriesDuration) { - super(jedisClusterNode, connectionTimeout, soTimeout, infiniteSoTimeout, maxAttempts, user, - password, clientName, poolConfig, ssl, sslSocketFactory, sslParameters, hostnameVerifier, - hostAndPortMap, maxTotalRetriesDuration); - } - - 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 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); - } +import com.fr.third.redis.clients.jedis.params.SetParams; +import com.fr.third.redis.clients.jedis.util.JedisClusterHashTagUtil; - @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); - } +public class JedisCluster extends BinaryJedisCluster implements JedisClusterCommands, + MultiKeyJedisClusterCommands, JedisClusterScriptingCommands { + + public JedisCluster(HostAndPort node) { + this(Collections.singleton(node)); + } + + public JedisCluster(HostAndPort node, int timeout) { + this(Collections.singleton(node), timeout); + } + + public JedisCluster(HostAndPort node, int timeout, int maxAttempts) { + this(Collections.singleton(node), timeout, maxAttempts); + } + + public JedisCluster(HostAndPort node, final GenericObjectPoolConfig poolConfig) { + this(Collections.singleton(node), 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) { + this(Collections.singleton(node), timeout, maxAttempts, poolConfig); + } + + public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, + int maxAttempts, 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) { + 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) { + this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, password, clientName, poolConfig); + } + + public JedisCluster(Set nodes) { + this(nodes, DEFAULT_TIMEOUT); + } + + public JedisCluster(Set nodes, int timeout) { + this(nodes, timeout, DEFAULT_MAX_ATTEMPTS); + } + + public JedisCluster(Set nodes, int timeout, int maxAttempts) { + this(nodes, timeout, maxAttempts, new GenericObjectPoolConfig()); + } + + public JedisCluster(Set nodes, final GenericObjectPoolConfig poolConfig) { + this(nodes, DEFAULT_TIMEOUT, DEFAULT_MAX_ATTEMPTS, poolConfig); + } + + public JedisCluster(Set nodes, int timeout, 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); + } + + 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, String password, String clientName, final GenericObjectPoolConfig poolConfig) { + super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, clientName, poolConfig); +} - @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 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) { - - 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>(connectionHandler, maxAttempts, - maxTotalRetriesDuration) { - @Override - public ScanResult execute(Jedis connection) { - return connection.scan(cursor, params); - } - }.run(matchPattern); - } - - @Override - public ScanResult> hscan(final String key, final String cursor) { - return new JedisClusterCommand>>(connectionHandler, - maxAttempts, maxTotalRetriesDuration) { - @Override - public ScanResult> execute(Jedis connection) { - return connection.hscan(key, cursor); - } - }.run(key); - } - - @Override - public ScanResult sscan(final String key, final String cursor) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public ScanResult execute(Jedis connection) { - return connection.sscan(key, cursor); - } - }.run(key); - } - - @Override - public ScanResult zscan(final String key, final String cursor) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public ScanResult execute(Jedis connection) { - return connection.zscan(key, cursor); - } - }.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); - } - - 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 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 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); - } - - private static String[] getKeys(final Map map) { - return map.keySet().toArray(new String[map.size()]); - } - - - //暴露出Client, 方便上层解耦 - public Client getClient() { - - Jedis jedis = this.connectionHandler.getConnection(); - if (jedis != null) { - return jedis.getClient(); - } - return null; - } + @Override + public String set(final String key, final String value) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @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) { + @Override + public String execute(Jedis connection) { + return connection.get(key); + } + }.run(key); + } + + @Override + public Boolean exists(final String key) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @Override + public Boolean execute(Jedis connection) { + return connection.exists(key); + } + }.run(key); + } + + @Override + public Long exists(final String... keys) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @Override + public Long execute(Jedis connection) { + return connection.persist(key); + } + }.run(key); + } + + @Override + public String type(final String key) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @Override + public String execute(Jedis connection) { + return connection.type(key); + } + }.run(key); + } + + @Override + public byte[] dump(final String key) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @Override + public byte[] execute(Jedis connection) { + return connection.dump(key); + } + }.run(key); + } + + @Override + public String restore(final String key, final int ttl, final byte[] serializedValue) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @Override + public String execute(Jedis connection) { + return connection.restore(key, ttl, serializedValue); + } + }.run(key); + } + + @Override + public Long expire(final String key, final int seconds) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @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) { + @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) { + @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) { + @Override + public Long execute(Jedis connection) { + return connection.ttl(key); + } + }.run(key); + } + + @Override + public Long pttl(final String key) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @Override + public Long execute(Jedis connection) { + return connection.pttl(key); + } + }.run(key); + } + + @Override + public Long touch(final String key) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @Override + public Long execute(Jedis connection) { + return connection.touch(key); + } + }.run(key); + } + + @Override + public Long touch(final String... keys) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @Override + public Long execute(Jedis connection) { + return connection.setnx(key, value); + } + }.run(key); + } + + @Override + public String setex(final String key, final int seconds, final String value) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @Override + public Long execute(Jedis connection) { + return connection.hincrBy(key, field, value); + } + }.run(key); + } + + @Override + public Boolean hexists(final String key, final String field) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @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) { + @Override + public Long execute(Jedis connection) { + return connection.hlen(key); + } + }.run(key); + } + + @Override + public Set hkeys(final String key) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { + @Override + public Set execute(Jedis connection) { + return connection.hkeys(key); + } + }.run(key); + } + + @Override + public List hvals(final String key) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { + @Override + public List execute(Jedis connection) { + return connection.hvals(key); + } + }.run(key); + } + + @Override + public Map hgetAll(final String key) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { + @Override + public Map execute(Jedis connection) { + return connection.hgetAll(key); + } + }.run(key); + } + + @Override + public Long rpush(final String key, final String... string) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @Override + public String execute(Jedis connection) { + return connection.lpop(key); + } + }.run(key); + } + + @Override + public String rpop(final String key) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @Override + public String execute(Jedis connection) { + return connection.rpop(key); + } + }.run(key); + } + + @Override + public Long sadd(final String key, final String... member) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @Override + public Boolean execute(Jedis connection) { + return connection.sismember(key, member); + } + }.run(key); + } + + @Override + public String srandmember(final String key) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @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) { + @Override + public Long execute(Jedis connection) { + return connection.strlen(key); + } + }.run(key); + } + + @Override + public Long zadd(final String key, final double score, final String member) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @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) { + @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) { + @Override + public Long execute(Jedis connection) { + return connection.zadd(key, scoreMembers, params); + } + }.run(key); + } + + @Override + public Set zrange(final String key, final long start, final long stop) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @Override + public Set execute(Jedis connection) { + return connection.zrevrangeWithScores(key, start, stop); + } + }.run(key); + } + + @Override + public Long zcard(final String key) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @Override + public Double execute(Jedis connection) { + return connection.zscore(key, member); + } + }.run(key); + } + + @Override + public List sort(final String key) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @Override + public Long execute(Jedis connection) { + return connection.del(key); + } + }.run(key); + } + + @Override + public Long unlink(final String key) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @Override + public Long execute(Jedis connection) { + return connection.unlink(key); + } + }.run(key); + } + + @Override + public Long unlink(final String... keys) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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 arbitary node + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @Override + public String execute(Jedis connection) { + return connection.echo(string); + } + }.run(string); + } + + @Override + public Long bitcount(final String key) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @Override + public Long execute(Jedis connection) { + return connection.bitcount(key, start, end); + } + }.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) { + @Override + public Set execute(Jedis connection) { + return connection.keys(pattern); + } + }.run(pattern); + } + + @Override + public ScanResult scan(final String cursor, final ScanParams params) { + + 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) { + @Override + public ScanResult execute(Jedis connection) { + return connection.scan(cursor, params); + } + }.run(matchPattern); + } + + @Override + public ScanResult> hscan(final String key, final String cursor) { + return new JedisClusterCommand>>(connectionHandler, + maxAttempts) { + @Override + public ScanResult> execute(Jedis connection) { + return connection.hscan(key, cursor); + } + }.run(key); + } + + @Override + public ScanResult sscan(final String key, final String cursor) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { + @Override + public ScanResult execute(Jedis connection) { + return connection.sscan(key, cursor); + } + }.run(key); + } + + @Override + public ScanResult zscan(final String key, final String cursor) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { + @Override + public ScanResult execute(Jedis connection) { + return connection.zscan(key, cursor); + } + }.run(key); + } + + @Override + public Long pfadd(final String key, final String... elements) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @Override + public Long execute(Jedis connection) { + return connection.pfcount(key); + } + }.run(key); + } + + @Override + public List blpop(final int timeout, final String key) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { + @Override + public List 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) { + @Override + public List execute(Jedis connection) { + return connection.brpop(timeout, key); + } + }.run(key); + } + + @Override + public Long del(final String... keys) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @Override + public Long execute(Jedis connection) { + return connection.del(keys); + } + }.run(keys.length, keys); + } + + @Override + public List blpop(final int timeout, final String... keys) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { + @Override + public List 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) { + @Override + public List execute(Jedis connection) { + return connection.brpop(timeout, keys); + } + }.run(keys.length, keys); + } + + @Override + public List mget(final String... keys) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @Override + public Long execute(Jedis connection) { + return connection.sunionstore(dstkey, keys); + } + }.run(wholeKeys.length, wholeKeys); + } + + @Override + public Long zinterstore(final String dstkey, final String... sets) { + String[] wholeKeys = KeyMergeUtil.merge(dstkey, sets); + + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @Override + public Long execute(Jedis connection) { + return connection.zinterstore(dstkey, params, sets); + } + }.run(mergedKeys.length, mergedKeys); + } + + @Override + public Long zunionstore(final String dstkey, final String... sets) { + String[] mergedKeys = KeyMergeUtil.merge(dstkey, sets); + + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @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) { + @Override + public String execute(Jedis connection) { + return connection.scriptLoad(script); + } + }.run(sampleKey); + } + + @Override + public String scriptFlush(final String sampleKey) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @Override + public String execute(Jedis connection) { + return connection.scriptFlush(); + } + }.run(sampleKey); + } + + @Override + public String scriptKill(final String sampleKey) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @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) { + @Override + public Long execute(Jedis connection) { + return connection.geoadd(key, memberCoordinateMap); + } + }.run(key); + } + + @Override + public Double geodist(final String key, final String member1, final String member2) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @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) { + @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) { + @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) { + @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) { + @Override + public List execute(Jedis connection) { + return connection.georadius(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) { + @Override + public List execute(Jedis connection) { + return connection.georadius(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) { + @Override + public List execute(Jedis connection) { + return connection.georadiusByMember(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) { + @Override + public List execute(Jedis connection) { + return connection.georadiusByMember(key, member, radius, unit, param); + } + }.run(key); + } + + @Override + public List bitfield(final String key, final String... arguments) { + return new JedisClusterCommand>(connectionHandler, maxAttempts) { + @Override + public List execute(Jedis connection) { + return connection.bitfield(key, arguments); + } + }.run(key); + } + + @Override + public Long hstrlen(final String key, final String field) { + return new JedisClusterCommand(connectionHandler, maxAttempts) { + @Override + public Long execute(Jedis connection) { + return connection.hstrlen(key, field); + } + }.run(key); + } + + //暴露出Client, 方便上层解耦 + public Client getClient() { + + Jedis jedis = this.connectionHandler.getConnection(); + if (jedis != null) { + return jedis.getClient(); + } + return null; + } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterCommand.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterCommand.java index 1c8b0bda1..cb56cba54 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterCommand.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterCommand.java @@ -1,11 +1,5 @@ package com.fr.third.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 com.fr.third.redis.clients.jedis.exceptions.JedisAskDataException; import com.fr.third.redis.clients.jedis.exceptions.JedisClusterMaxAttemptsException; import com.fr.third.redis.clients.jedis.exceptions.JedisClusterOperationException; @@ -17,37 +11,30 @@ import com.fr.third.redis.clients.jedis.util.JedisClusterCRC16; public abstract class JedisClusterCommand { - private static final Logger LOG = LoggerFactory.getLogger(JedisClusterCommand.class); + private static final String NO_DISPATCH_MESSAGE = "No way to dispatch this command to Redis Cluster."; private final JedisClusterConnectionHandler connectionHandler; private final int maxAttempts; - private final Duration maxTotalRetriesDuration; + private final ThreadLocal askConnection = new ThreadLocal(); 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)); + if (key == null) { + throw new JedisClusterOperationException(NO_DISPATCH_MESSAGE); + } + + return runWithRetries(JedisClusterCRC16.getSlot(key), this.maxAttempts, false, false); } 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."); + throw new JedisClusterOperationException(NO_DISPATCH_MESSAGE); } // For multiple keys, only execute if they all share the same connection slot. @@ -62,16 +49,20 @@ public abstract class JedisClusterCommand { } } - return runWithRetries(slot); + return runWithRetries(slot, this.maxAttempts, false, false); } public T runBinary(byte[] key) { - return runWithRetries(JedisClusterCRC16.getSlot(key)); + if (key == null) { + throw new JedisClusterOperationException(NO_DISPATCH_MESSAGE); + } + + return runWithRetries(JedisClusterCRC16.getSlot(key), this.maxAttempts, false, false); } 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."); + throw new JedisClusterOperationException(NO_DISPATCH_MESSAGE); } // For multiple keys, only execute if they all share the same connection slot. @@ -86,7 +77,7 @@ public abstract class JedisClusterCommand { } } - return runWithRetries(slot); + return runWithRetries(slot, this.maxAttempts, false, false); } public T runWithAnyNode() { @@ -94,125 +85,79 @@ public abstract class JedisClusterCommand { try { connection = connectionHandler.getConnection(); return execute(connection); + } catch (JedisConnectionException e) { + throw e; } 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(); - } + private T runWithRetries(final int slot, int attempts, boolean tryRandomNode, boolean asking) { + if (attempts <= 0) { + throw new JedisClusterMaxAttemptsException("No more cluster attempts left."); + } + + Jedis connection = null; + try { + + if (asking) { + // TODO: Pipeline asking with the original command to make it + // faster.... + connection = askConnection.get(); + connection.asking(); + + // if asking success, reset asking flag + asking = false; + } else { + if (tryRandomNode) { + connection = connectionHandler.getConnection(); } else { connection = connectionHandler.getConnectionFromSlot(slot); } - - return execute(connection); - - } catch (JedisNoReachableClusterNodeException 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 - 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; - } + return execute(connection); - /** - * 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) { + } catch (JedisNoReachableClusterNodeException jnrcne) { + throw jnrcne; + } catch (JedisConnectionException jce) { + // release current connection before recursion + releaseConnection(connection); + connection = null; + + if (attempts <= 1) { + //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. + //But now if maxAttempts = 1 or 2 we will do it too often. For each time-outed request. + //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; } - 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 runWithRetries(slot, attempts - 1, tryRandomNode, asking); + } catch (JedisRedirectionException jre) { + // if MOVED redirection occurred, + if (jre instanceof JedisMovedDataException) { + // it rebuilds cluster's slot cache + // recommended by Redis cluster specification + this.connectionHandler.renewSlotCache(connection); + } - return millisLeft / (attemptsLeft * (attemptsLeft + 1)); - } + // release current connection before recursion or renewing + releaseConnection(connection); + connection = null; + + if (jre instanceof JedisAskDataException) { + asking = true; + askConnection.set(this.connectionHandler.getConnectionFromNode(jre.getTargetNode())); + } else if (jre instanceof JedisMovedDataException) { + } else { + throw new JedisClusterOperationException(jre); + } - protected void sleep(long sleepMillis) { - try { - TimeUnit.MILLISECONDS.sleep(sleepMillis); - } catch (InterruptedException e) { - throw new JedisClusterOperationException(e); + return runWithRetries(slot, attempts - 1, false, asking); + } finally { + releaseConnection(connection); } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterConnectionHandler.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterConnectionHandler.java index cef4309e8..0bfdd39a0 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterConnectionHandler.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterConnectionHandler.java @@ -1,13 +1,8 @@ package com.fr.third.redis.clients.jedis; import java.io.Closeable; -import java.util.ArrayList; -import java.util.Collections; import java.util.Map; import java.util.Set; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLParameters; -import javax.net.ssl.SSLSocketFactory; import com.fr.third.org.apache.commons.pool2.impl.GenericObjectPoolConfig; @@ -17,117 +12,48 @@ public abstract class JedisClusterConnectionHandler implements Closeable { protected final JedisClusterInfoCache cache; public JedisClusterConnectionHandler(Set nodes, - GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, - String password) { + final 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, connectionTimeout, soTimeout, infiniteSoTimeout, user, password, - clientName, false, null, null, null, null); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public JedisClusterConnectionHandler(Set nodes, - GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, - String password, String clientName, boolean ssl, SSLSocketFactory sslSocketFactory, - SSLParameters sslParameters, HostnameVerifier hostnameVerifier, - JedisClusterHostAndPortMap portMap) { - this(nodes, poolConfig, connectionTimeout, soTimeout, null, password, clientName, ssl, - sslSocketFactory, sslParameters, hostnameVerifier, portMap); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public JedisClusterConnectionHandler(Set nodes, - GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, String user, - String password, String clientName, boolean ssl, SSLSocketFactory sslSocketFactory, - SSLParameters sslParameters, HostnameVerifier hostnameVerifier, - JedisClusterHostAndPortMap portMap) { - this(nodes, poolConfig, connectionTimeout, soTimeout, 0, user, password, clientName, ssl, - sslSocketFactory, sslParameters, hostnameVerifier, portMap); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public JedisClusterConnectionHandler(Set nodes, - final GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, - int infiniteSoTimeout, String user, String password, String clientName, boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier, JedisClusterHostAndPortMap portMap) { - this(nodes, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) - .socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout) - .user(user).password(password).clientName(clientName).ssl(ssl) - .sslSocketFactory(sslSocketFactory).sslParameters(sslParameters) - .hostnameVerifier(hostnameVerifier).build(), poolConfig, DefaultJedisClientConfig - .builder().connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout) - .blockingSocketTimeoutMillis(infiniteSoTimeout).user(user).password(password) - .clientName(clientName).ssl(ssl).sslSocketFactory(sslSocketFactory) - .sslParameters(sslParameters).hostnameVerifier(hostnameVerifier) - .hostAndPortMapper(portMap).build()); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public JedisClusterConnectionHandler(Set nodes, - final JedisClientConfig seedNodesClientConfig, - final GenericObjectPoolConfig poolConfig, - final JedisClientConfig clusterNodesClientConfig) { - this.cache = new JedisClusterInfoCache(poolConfig, clusterNodesClientConfig); - initializeSlotsCache(nodes, seedNodesClientConfig); - } - - public JedisClusterConnectionHandler(Set nodes, - final GenericObjectPoolConfig poolConfig, final JedisClientConfig clientConfig) { - this.cache = new JedisClusterInfoCache(poolConfig, clientConfig); - initializeSlotsCache(nodes, clientConfig); - } + final GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, String password, String clientName) { + this.cache = new JedisClusterInfoCache(poolConfig, connectionTimeout, soTimeout, password, clientName); + initializeSlotsCache(nodes, poolConfig, connectionTimeout, soTimeout, password, clientName); +} - protected abstract Jedis getConnection(); + abstract Jedis getConnection(); - protected abstract Jedis getConnectionFromSlot(int slot); + 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)) { + private void initializeSlotsCache(Set startNodes, GenericObjectPoolConfig poolConfig, + int connectionTimeout, int soTimeout, String password, String clientName) { + for (HostAndPort hostAndPort : startNodes) { + Jedis jedis = null; + try { + jedis = new Jedis(hostAndPort.getHost(), hostAndPort.getPort(), connectionTimeout, soTimeout); + if (password != null) { + jedis.auth(password); + } + if (clientName != null) { + jedis.clientSetname(clientName); + } cache.discoverClusterNodesAndSlots(jedis); - return; + break; } catch (JedisConnectionException e) { // try next nodes + } finally { + if (jedis != null) { + jedis.close(); + } } } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterHostAndPortMap.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterHostAndPortMap.java deleted file mode 100644 index ff0d20d27..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterHostAndPortMap.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.fr.third.redis.clients.jedis; - -/** - * @deprecated This will be removed in future. Prefer to use {@link HostAndPortMapper} instead. - */ -@Deprecated -public interface JedisClusterHostAndPortMap extends HostAndPortMapper { - - HostAndPort getSSLHostAndPort(String host, int port); - - @Override - default HostAndPort getHostAndPort(HostAndPort hap) { - return getSSLHostAndPort(hap.getHost(), hap.getPort()); - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterInfoCache.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterInfoCache.java index c2b6bd4e4..24ef2eeb0 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterInfoCache.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterInfoCache.java @@ -7,9 +7,6 @@ import java.util.List; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLParameters; -import javax.net.ssl.SSLSocketFactory; import com.fr.third.org.apache.commons.pool2.impl.GenericObjectPoolConfig; @@ -18,123 +15,33 @@ import com.fr.third.redis.clients.jedis.exceptions.JedisException; import com.fr.third.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 ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); private final Lock r = rwl.readLock(); private final Lock w = rwl.writeLock(); private volatile boolean rediscovering; + private final GenericObjectPoolConfig poolConfig; - private final GenericObjectPoolConfig poolConfig; - private final JedisClientConfig clientConfig; + private int connectionTimeout; + private int soTimeout; + private String password; + private String clientName; private static final int MASTER_NODE_INDEX = 2; - public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig, int timeout) { + 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); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - 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, - JedisClusterHostAndPortMap 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 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); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - 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, - JedisClusterHostAndPortMap 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 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); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - 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, JedisClusterHostAndPortMap hostAndPortMap) { - this(poolConfig, connectionTimeout, soTimeout, infiniteSoTimeout, user, password, clientName, - ssl, sslSocketFactory, sslParameters, hostnameVerifier, (HostAndPortMapper) 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 GenericObjectPoolConfig poolConfig, - final JedisClientConfig clientConfig) { + public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig, + final int connectionTimeout, final int soTimeout, final String password, final String clientName) { this.poolConfig = poolConfig; - this.clientConfig = clientConfig; + this.connectionTimeout = connectionTimeout; + this.soTimeout = soTimeout; + this.password = password; + this.clientName = clientName; } public void discoverClusterNodesAndSlots(Jedis jedis) { @@ -157,7 +64,7 @@ public class JedisClusterInfoCache { int size = slotInfo.size(); for (int i = MASTER_NODE_INDEX; i < size; i++) { List hostInfos = (List) slotInfo.get(i); - if (hostInfos.isEmpty()) { + if (hostInfos.size() <= 0) { continue; } @@ -174,42 +81,37 @@ public class JedisClusterInfoCache { } public void renewClusterSlots(Jedis jedis) { - // If rediscovering is already in process - no need to start one more same rediscovering, just return + //If rediscovering is already in process - no need to start one more same rediscovering, just return if (!rediscovering) { try { w.lock(); - if (!rediscovering) { - rediscovering = true; + rediscovering = true; + if (jedis != null) { try { - if (jedis != null) { - try { - discoverClusterSlots(jedis); - return; - } catch (JedisException e) { - // try nodes from all pools - } - } + discoverClusterSlots(jedis); + return; + } catch (JedisException e) { + //try nodes from all pools + } + } - for (JedisPool jp : getShuffledNodesPool()) { - Jedis j = null; - try { - j = jp.getResource(); - discoverClusterSlots(j); - return; - } catch (JedisConnectionException e) { - // try next nodes - } finally { - if (j != null) { - j.close(); - } - } - } + for (JedisPool jp : getShuffledNodesPool()) { + Jedis j = null; + try { + j = jp.getResource(); + discoverClusterSlots(j); + return; + } catch (JedisConnectionException e) { + // try next nodes } finally { - rediscovering = false; + if (j != null) { + j.close(); + } } } } finally { + rediscovering = false; w.unlock(); } } @@ -241,19 +143,19 @@ public class JedisClusterInfoCache { } private HostAndPort generateHostAndPort(List hostInfos) { - String host = SafeEncoder.encode((byte[]) hostInfos.get(0)); - int port = ((Long) hostInfos.get(1)).intValue(); - return new HostAndPort(host, port); + return new HostAndPort(SafeEncoder.encode((byte[]) hostInfos.get(0)), + ((Long) hostInfos.get(1)).intValue()); } - public JedisPool setupNodeIfNotExist(final HostAndPort node) { + public JedisPool setupNodeIfNotExist(HostAndPort node) { w.lock(); try { String nodeKey = getNodeKey(node); JedisPool existingPool = nodes.get(nodeKey); if (existingPool != null) return existingPool; - JedisPool nodePool = new JedisPool(poolConfig, node, clientConfig); + JedisPool nodePool = new JedisPool(poolConfig, node.getHost(), node.getPort(), + connectionTimeout, soTimeout, password, 0, clientName, false, null, null, null); nodes.put(nodeKey, nodePool); return nodePool; } finally { @@ -304,7 +206,7 @@ public class JedisClusterInfoCache { public Map getNodes() { r.lock(); try { - return new HashMap<>(nodes); + return new HashMap(nodes); } finally { r.unlock(); } @@ -313,7 +215,7 @@ public class JedisClusterInfoCache { public List getShuffledNodesPool() { r.lock(); try { - List pools = new ArrayList<>(nodes.values()); + List pools = new ArrayList(nodes.values()); Collections.shuffle(pools); return pools; } finally { @@ -347,24 +249,16 @@ public class JedisClusterInfoCache { return hnp.getHost() + ":" + hnp.getPort(); } - /** - * @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 getAssignedSlotArray(List slotInfo) { - List slotNums = new ArrayList<>(); + List slotNums = new ArrayList(); for (int slot = ((Long) slotInfo.get(0)).intValue(); slot <= ((Long) slotInfo.get(1)) .intValue(); slot++) { slotNums.add(slot); diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisFactory.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisFactory.java index 50e10f27f..22343bae1 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisFactory.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisFactory.java @@ -1,6 +1,7 @@ package com.fr.third.redis.clients.jedis; import java.net.URI; +import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLParameters; @@ -9,8 +10,6 @@ import javax.net.ssl.SSLSocketFactory; import com.fr.third.org.apache.commons.pool2.PooledObject; import com.fr.third.org.apache.commons.pool2.PooledObjectFactory; import com.fr.third.org.apache.commons.pool2.impl.DefaultPooledObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.fr.third.redis.clients.jedis.exceptions.InvalidURIException; import com.fr.third.redis.clients.jedis.exceptions.JedisException; @@ -19,135 +18,76 @@ import com.fr.third.redis.clients.jedis.util.JedisURIHelper; /** * PoolableObjectFactory custom impl. */ -public class JedisFactory implements PooledObjectFactory { - - private static final Logger logger = LoggerFactory.getLogger(JedisFactory.class); - - private final JedisSocketFactory jedisSocketFactory; - - private final JedisClientConfig clientConfig; - - protected JedisFactory(final String host, final int port, final int connectionTimeout, +class JedisFactory implements PooledObjectFactory { + private final AtomicReference hostAndPort = new AtomicReference(); + private final int connectionTimeout; + private final int soTimeout; + private final String password; + private final int database; + private final String clientName; + private final boolean ssl; + private final SSLSocketFactory sslSocketFactory; + private final SSLParameters sslParameters; + private final HostnameVerifier hostnameVerifier; + + JedisFactory(final String host, final int port, final int connectionTimeout, final int soTimeout, final String password, final int database, final String clientName) { - this(host, port, connectionTimeout, soTimeout, password, database, clientName, false, null, null, null); - } - - protected JedisFactory(final String host, final int port, final int connectionTimeout, - final int soTimeout, final String user, final String password, final int database, final String clientName) { - this(host, port, connectionTimeout, soTimeout, 0, user, password, database, clientName); - } - - protected JedisFactory(final String host, final int port, final int connectionTimeout, final int soTimeout, - final int infiniteSoTimeout, final String user, final String password, final int database, final String clientName) { - this(host, port, connectionTimeout, soTimeout, infiniteSoTimeout, user, password, database, clientName, false, null, null, null); - } - - /** - * {@link #setHostAndPort(redis.clients.jedis.HostAndPort) setHostAndPort} must be called later. - */ - protected 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); + this(host, port, connectionTimeout, soTimeout, password, database, clientName, + false, null, null, null); } - protected JedisFactory(final String host, final int port, final int connectionTimeout, + JedisFactory(final String host, final 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(host, port, connectionTimeout, soTimeout, null, password, database, clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier); - } - - protected JedisFactory(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, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, - final HostnameVerifier hostnameVerifier) { - this(host, port, connectionTimeout, soTimeout, 0, user, password, database, clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier); - } - - protected JedisFactory(final HostAndPort hostAndPort, final JedisClientConfig clientConfig) { - this.clientConfig = DefaultJedisClientConfig.copyConfig(clientConfig); - this.jedisSocketFactory = new DefaultJedisSocketFactory(hostAndPort, this.clientConfig); - } - - protected JedisFactory(final String host, final 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.clientConfig = DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) - .socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout).user(user) - .password(password).database(database).clientName(clientName) - .ssl(ssl).sslSocketFactory(sslSocketFactory) - .sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build(); - this.jedisSocketFactory = new DefaultJedisSocketFactory(new HostAndPort(host, port), this.clientConfig); - } - - protected JedisFactory(final JedisSocketFactory jedisSocketFactory, final JedisClientConfig clientConfig) { - this.clientConfig = DefaultJedisClientConfig.copyConfig(clientConfig); - this.jedisSocketFactory = jedisSocketFactory; - } - - /** - * {@link #setHostAndPort(redis.clients.jedis.HostAndPort) setHostAndPort} must be called later. - */ - protected 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) - .socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout).user(user) - .password(password).database(database).clientName(clientName) - .ssl(ssl).sslSocketFactory(sslSocketFactory) - .sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build()); - } - - /** - * {@link #setHostAndPort(redis.clients.jedis.HostAndPort) setHostAndPort} must be called later. - */ - protected JedisFactory(final JedisClientConfig clientConfig) { - this.clientConfig = clientConfig; - this.jedisSocketFactory = new DefaultJedisSocketFactory(clientConfig); - } - - protected JedisFactory(final URI uri, final int connectionTimeout, final int soTimeout, + this.hostAndPort.set(new HostAndPort(host, port)); + this.connectionTimeout = connectionTimeout; + this.soTimeout = soTimeout; + this.password = password; + this.database = database; + this.clientName = clientName; + this.ssl = ssl; + this.sslSocketFactory = sslSocketFactory; + this.sslParameters = sslParameters; + this.hostnameVerifier = hostnameVerifier; + } + + JedisFactory(final URI uri, final int connectionTimeout, final int soTimeout, final String clientName) { this(uri, connectionTimeout, soTimeout, clientName, null, null, null); } - protected JedisFactory(final URI uri, final int connectionTimeout, final int soTimeout, + JedisFactory(final URI uri, final int connectionTimeout, final int soTimeout, final String clientName, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - this(uri, connectionTimeout, soTimeout, 0, clientName, sslSocketFactory, sslParameters, hostnameVerifier); - } - - protected JedisFactory(final URI uri, final int connectionTimeout, final int soTimeout, - final int infiniteSoTimeout, final String clientName, final SSLSocketFactory sslSocketFactory, - final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { if (!JedisURIHelper.isValid(uri)) { throw new InvalidURIException(String.format( - "Cannot open Redis connection due invalid URI. %s", uri.toString())); + "Cannot open Redis connection due invalid URI. %s", uri.toString())); } - this.clientConfig = DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) - .socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout) - .user(JedisURIHelper.getUser(uri)).password(JedisURIHelper.getPassword(uri)) - .database(JedisURIHelper.getDBIndex(uri)).clientName(clientName) - .ssl(JedisURIHelper.isRedisSSLScheme(uri)).sslSocketFactory(sslSocketFactory) - .sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build(); - this.jedisSocketFactory = new DefaultJedisSocketFactory(new HostAndPort(uri.getHost(), uri.getPort()), this.clientConfig); - } - public void setHostAndPort(final HostAndPort hostAndPort) { - jedisSocketFactory.updateHostAndPort(hostAndPort); + this.hostAndPort.set(new HostAndPort(uri.getHost(), uri.getPort())); + this.connectionTimeout = connectionTimeout; + this.soTimeout = soTimeout; + this.password = JedisURIHelper.getPassword(uri); + this.database = JedisURIHelper.getDBIndex(uri); + this.clientName = clientName; + this.ssl = JedisURIHelper.isRedisSSLScheme(uri); + this.sslSocketFactory = sslSocketFactory; + this.sslParameters = sslParameters; + this.hostnameVerifier = hostnameVerifier; } - public void setPassword(final String password) { - this.clientConfig.updatePassword(password); + public void setHostAndPort(final HostAndPort hostAndPort) { + this.hostAndPort.set(hostAndPort); } @Override public void activateObject(PooledObject pooledJedis) throws Exception { final BinaryJedis jedis = pooledJedis.getObject(); - if (jedis.getDB() != clientConfig.getDatabase()) { - jedis.select(clientConfig.getDatabase()); + if (jedis.getDB() != database) { + jedis.select(database); } + } @Override @@ -155,43 +95,42 @@ public class JedisFactory implements PooledObjectFactory { final BinaryJedis jedis = pooledJedis.getObject(); if (jedis.isConnected()) { try { - // need a proper test, probably with mock - if (!jedis.isBroken()) { + try { jedis.quit(); + } catch (Exception e) { } + jedis.disconnect(); } catch (Exception e) { - logger.warn("Error while QUIT", e); - } - try { - jedis.close(); - } catch (Exception e) { - logger.warn("Error while close", e); + } } + } @Override public PooledObject makeObject() throws Exception { - Jedis jedis = null; + final HostAndPort hostAndPort = this.hostAndPort.get(); + final Jedis jedis = new Jedis(hostAndPort.getHost(), hostAndPort.getPort(), connectionTimeout, + soTimeout, ssl, sslSocketFactory, sslParameters, hostnameVerifier); + try { - jedis = new Jedis(jedisSocketFactory, clientConfig); jedis.connect(); - return new DefaultPooledObject<>(jedis); - } catch (JedisException je) { - if (jedis != null) { - try { - jedis.quit(); - } catch (Exception e) { - logger.warn("Error while QUIT", e); - } - try { - jedis.close(); - } catch (Exception e) { - logger.warn("Error while close", e); - } + if (password != null) { + jedis.auth(password); + } + if (database != 0) { + jedis.select(database); + } + if (clientName != null) { + jedis.clientSetname(clientName); } + } catch (JedisException je) { + jedis.close(); throw je; } + + return new DefaultPooledObject(jedis); + } @Override @@ -203,18 +142,16 @@ public class JedisFactory implements PooledObjectFactory { public boolean validateObject(PooledObject pooledJedis) { final BinaryJedis jedis = pooledJedis.getObject(); try { - String host = jedisSocketFactory.getHost(); - int port = jedisSocketFactory.getPort(); + HostAndPort hostAndPort = this.hostAndPort.get(); String connectionHost = jedis.getClient().getHost(); int connectionPort = jedis.getClient().getPort(); - return host.equals(connectionHost) - && port == connectionPort && jedis.isConnected() + return hostAndPort.getHost().equals(connectionHost) + && hostAndPort.getPort() == connectionPort && jedis.isConnected() && jedis.ping().equals("PONG"); } catch (final Exception e) { - logger.error("Error while validating pooled Jedis object.", e); return false; } } -} +} \ No newline at end of file diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPool.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPool.java index 252403236..47a37c46b 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPool.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPool.java @@ -1,124 +1,87 @@ package com.fr.third.redis.clients.jedis; import java.net.URI; + import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocketFactory; -import com.fr.third.org.apache.commons.pool2.PooledObjectFactory; +import com.fr.third.org.apache.commons.pool2.impl.GenericObjectPool; import com.fr.third.org.apache.commons.pool2.impl.GenericObjectPoolConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import com.fr.third.redis.clients.jedis.exceptions.JedisException; import com.fr.third.redis.clients.jedis.util.JedisURIHelper; public class JedisPool extends JedisPoolAbstract { - private static final Logger log = LoggerFactory.getLogger(JedisPool.class); - public JedisPool() { this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT); } - public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) { + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) { this(poolConfig, host, Protocol.DEFAULT_PORT); } public JedisPool(String host, int port) { - this(new GenericObjectPoolConfig(), host, port); + this(new GenericObjectPoolConfig(), host, port); } - /** - * @param url - * @deprecated This constructor will not accept a host string in future. It will accept only a uri - * string. You can use {@link JedisURIHelper#isValid(java.net.URI)} before this. - */ - @Deprecated - public JedisPool(final String url) { - URI uri = URI.create(url); + public JedisPool(final String host) { + URI uri = URI.create(host); if (JedisURIHelper.isValid(uri)) { - initPool(new GenericObjectPoolConfig(), new JedisFactory(uri, - Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null)); + this.internalPool = new GenericObjectPool(new JedisFactory(uri, + Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null), new GenericObjectPoolConfig()); } else { - initPool(new GenericObjectPoolConfig(), new JedisFactory(url, Protocol.DEFAULT_PORT, - Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null)); + this.internalPool = new GenericObjectPool(new JedisFactory(host, + Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null, + Protocol.DEFAULT_DATABASE, null), new GenericObjectPoolConfig()); } } - /** - * @param url - * @param sslSocketFactory - * @param sslParameters - * @param hostnameVerifier - * @deprecated This constructor will not accept a host string in future. It will accept only a uri - * string. You can use {@link JedisURIHelper#isValid(java.net.URI)} before this. - */ - @Deprecated - public JedisPool(final String url, final SSLSocketFactory sslSocketFactory, + public JedisPool(final String host, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - URI uri = URI.create(url); + URI uri = URI.create(host); if (JedisURIHelper.isValid(uri)) { - initPool(new GenericObjectPoolConfig(), new JedisFactory(uri, - Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null, sslSocketFactory, - sslParameters, hostnameVerifier)); + this.internalPool = new GenericObjectPool(new JedisFactory(uri, + Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null, sslSocketFactory, sslParameters, + hostnameVerifier), new GenericObjectPoolConfig()); } else { - initPool(new GenericObjectPoolConfig(), new JedisFactory(url, Protocol.DEFAULT_PORT, - Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null, - false, null, null, null)); + this.internalPool = new GenericObjectPool(new JedisFactory(host, + Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null, + Protocol.DEFAULT_DATABASE, null, false, null, null, null), new GenericObjectPoolConfig()); } } public JedisPool(final URI uri) { - this(new GenericObjectPoolConfig(), uri); + this(new GenericObjectPoolConfig(), uri); } public JedisPool(final URI uri, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - this(new GenericObjectPoolConfig(), uri, sslSocketFactory, sslParameters, - hostnameVerifier); + this(new GenericObjectPoolConfig(), uri, sslSocketFactory, sslParameters, hostnameVerifier); } public JedisPool(final URI uri, final int timeout) { - this(new GenericObjectPoolConfig(), uri, timeout); + this(new GenericObjectPoolConfig(), uri, timeout); } public JedisPool(final URI uri, final int timeout, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - this(new GenericObjectPoolConfig(), uri, timeout, sslSocketFactory, sslParameters, + this(new GenericObjectPoolConfig(), uri, timeout, sslSocketFactory, sslParameters, hostnameVerifier); } - public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, int timeout, final String password) { this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE); } - public JedisPool(final String host, int port, String user, final String password) { - this(new GenericObjectPoolConfig(), host, port, user, password); - } - - public JedisPool(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 JedisPool(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 JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + public JedisPool(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 JedisPool(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 JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + public JedisPool(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) { @@ -126,62 +89,50 @@ public class JedisPool extends JedisPoolAbstract { sslSocketFactory, sslParameters, hostnameVerifier); } - public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, - final int port) { + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port) { this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT); } - public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, - final int port, final boolean ssl) { + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port, + final boolean ssl) { this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, ssl); } - public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, - final int port, final boolean ssl, final SSLSocketFactory sslSocketFactory, - final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + public JedisPool(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 JedisPool(final GenericObjectPoolConfig poolConfig, final String host, - final int port, final int timeout) { + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port, + final int timeout) { this(poolConfig, host, port, timeout, null); } - public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, - final int port, final int timeout, final boolean ssl) { + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port, + final int timeout, final boolean ssl) { this(poolConfig, host, port, timeout, null, ssl); } - public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, - final int port, final int timeout, final boolean ssl, - final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, - final HostnameVerifier hostnameVerifier) { + public JedisPool(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 JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + public JedisPool(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 JedisPool(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 JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + public JedisPool(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 JedisPool(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 JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + public JedisPool(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) { @@ -189,30 +140,18 @@ public class JedisPool extends JedisPoolAbstract { sslParameters, hostnameVerifier); } - public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + public JedisPool(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 JedisPool(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 JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + public JedisPool(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 JedisPool(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 JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + public JedisPool(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) { @@ -220,7 +159,7 @@ public class JedisPool extends JedisPoolAbstract { sslSocketFactory, sslParameters, hostnameVerifier); } - public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + public JedisPool(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) { @@ -228,139 +167,68 @@ public class JedisPool extends JedisPoolAbstract { database, clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier)); } - public JedisPool(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 JedisPool(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 JedisPool(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) { - super(poolConfig, new JedisFactory(host, port, connectionTimeout, soTimeout, infiniteSoTimeout, - user, password, database, clientName, ssl, sslSocketFactory, sslParameters, - hostnameVerifier)); - } - - public JedisPool(final GenericObjectPoolConfig poolConfig, final HostAndPort hostAndPort, - final JedisClientConfig clientConfig) { - super(poolConfig, new JedisFactory(hostAndPort, clientConfig)); - } - - public JedisPool(final GenericObjectPoolConfig poolConfig, final JedisSocketFactory jedisSocketFactory, - final JedisClientConfig clientConfig) { - super(poolConfig, new JedisFactory(jedisSocketFactory, clientConfig)); - } - - public JedisPool(final GenericObjectPoolConfig poolConfig) { + public JedisPool(final GenericObjectPoolConfig poolConfig) { this(poolConfig, Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT); } public JedisPool(final String host, final int port, final boolean ssl) { - this(new GenericObjectPoolConfig(), host, port, ssl); + this(new GenericObjectPoolConfig(), host, port, ssl); } - public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, final int connectionTimeout, final int soTimeout, final String password, final int database, final String clientName) { super(poolConfig, new JedisFactory(host, port, connectionTimeout, soTimeout, password, database, clientName)); } - public JedisPool(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) { - super(poolConfig, new JedisFactory(host, port, connectionTimeout, soTimeout, user, password, - database, clientName)); - } - - public JedisPool(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) { - super(poolConfig, new JedisFactory(host, port, connectionTimeout, soTimeout, infiniteSoTimeout, - user, password, database, clientName)); - } - public JedisPool(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, + this(new GenericObjectPoolConfig(), host, port, ssl, sslSocketFactory, sslParameters, hostnameVerifier); } - public JedisPool(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) { + public JedisPool(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 JedisPool(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 JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri) { + public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri) { this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT); } - public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, + public JedisPool(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 JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int timeout) { + public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int timeout) { this(poolConfig, uri, timeout, timeout); } - public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, - final int timeout, final SSLSocketFactory sslSocketFactory, - final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + public JedisPool(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 JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, + public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int connectionTimeout, final int soTimeout) { - this(poolConfig, uri, connectionTimeout, soTimeout, null, null, null); + super(poolConfig, new JedisFactory(uri, connectionTimeout, soTimeout, null)); } - public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, + public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int connectionTimeout, final int soTimeout, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { super(poolConfig, new JedisFactory(uri, connectionTimeout, soTimeout, null, sslSocketFactory, sslParameters, hostnameVerifier)); } - public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, - final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, - final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, - final HostnameVerifier hostnameVerifier) { - super(poolConfig, new JedisFactory(uri, connectionTimeout, soTimeout, infiniteSoTimeout, null, - sslSocketFactory, sslParameters, hostnameVerifier)); - } - - public JedisPool(GenericObjectPoolConfig poolConfig, PooledObjectFactory factory) { - super(poolConfig, factory); - } - @Override public Jedis getResource() { Jedis jedis = super.getResource(); @@ -369,14 +237,21 @@ public class JedisPool extends JedisPoolAbstract { } @Override - public void returnResource(final Jedis resource) { + protected void returnBrokenResource(final Jedis resource) { + if (resource != null) { + returnBrokenResourceObject(resource); + } + } + + @Override + protected void returnResource(final Jedis resource) { if (resource != null) { try { resource.resetState(); returnResourceObject(resource); } catch (Exception e) { returnBrokenResource(resource); - log.warn("Resource is returned to the pool as broken", e); + throw new JedisException("Could not return the resource to the pool", e); } } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPoolAbstract.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPoolAbstract.java index f174d1a7c..9d321f911 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPoolAbstract.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPoolAbstract.java @@ -5,25 +5,23 @@ import com.fr.third.org.apache.commons.pool2.impl.GenericObjectPoolConfig; import com.fr.third.redis.clients.jedis.util.Pool; -/** - * @deprecated This class will be removed in future. If you are directly manipulating this class, - * you are suggested to change your code to use {@link Pool Pool<Jedis>} instead. - */ -@Deprecated public class JedisPoolAbstract extends Pool { - /** - * Using this constructor means you have to set and initialize the internalPool yourself. - * - * @deprecated This constructor will be removed in future. - */ - @Deprecated public JedisPoolAbstract() { super(); } - public JedisPoolAbstract(GenericObjectPoolConfig poolConfig, - PooledObjectFactory factory) { + public JedisPoolAbstract(GenericObjectPoolConfig poolConfig, PooledObjectFactory factory) { super(poolConfig, factory); } + + @Override + protected void returnBrokenResource(Jedis resource) { + super.returnBrokenResource(resource); + } + + @Override + protected void returnResource(Jedis resource) { + super.returnResource(resource); + } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPoolConfig.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPoolConfig.java index 80424c33b..ccbf7aad1 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPoolConfig.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPoolConfig.java @@ -2,7 +2,7 @@ package com.fr.third.redis.clients.jedis; import com.fr.third.org.apache.commons.pool2.impl.GenericObjectPoolConfig; -public class JedisPoolConfig extends GenericObjectPoolConfig { +public class JedisPoolConfig extends GenericObjectPoolConfig { public JedisPoolConfig() { // defaults to make your life with connection pool easier :) setTestWhileIdle(true); diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPubSub.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPubSub.java index 377797df5..dd23d2f69 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPubSub.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPubSub.java @@ -17,179 +17,171 @@ import com.fr.third.redis.clients.jedis.util.SafeEncoder; 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 static final String JEDIS_SUBSCRIPTION_MESSAGE = "JedisPubSub is not subscribed to a Jedis instance."; + private int subscribedChannels = 0; + private volatile Client client; - public JedisPubSub() { + public JedisPubSub() { - } - - public JedisPubSub(Client client) { - this.client = client; - } - - public void onMessage(String channel, String message) { - } - - public void onPMessage(String pattern, String channel, String message) { - } - - public void onSubscribe(String channel, int subscribedChannels) { - } - - public void onUnsubscribe(String channel, int subscribedChannels) { - } - - public void onPUnsubscribe(String pattern, int subscribedChannels) { - } - - public void onPSubscribe(String pattern, int subscribedChannels) { - } + } - public void onPong(String pattern) { + public JedisPubSub(Client client) { + this.client = client; + } - } + public void onMessage(String channel, String message) { + } - public void unsubscribe() { - if (client == null) { - throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); - } - client.unsubscribe(); - client.flush(); - } + public void onPMessage(String pattern, String channel, String message) { + } - public void unsubscribe(String... channels) { - if (client == null) { - throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); - } - client.unsubscribe(channels); - client.flush(); - } - - public void subscribe(String... channels) { - if (client == null) { - throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); - } - client.subscribe(channels); - client.flush(); - } + public void onSubscribe(String channel, int subscribedChannels) { + } - public void psubscribe(String... patterns) { - if (client == null) { - throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); - } - client.psubscribe(patterns); - client.flush(); - } - - public void punsubscribe() { - if (client == null) { - throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); - } - client.punsubscribe(); - client.flush(); - } - - public void punsubscribe(String... patterns) { - if (client == null) { - throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); - } - client.punsubscribe(patterns); - client.flush(); - } - - public void ping() { - if (client == null) { - throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); - } - client.ping(); - client.flush(); - } - - public void ping(String argument) { - if (client == null) { - throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); - } - client.ping(argument); - client.flush(); - } - - public boolean isSubscribed() { - return subscribedChannels > 0; - } - - public void proceedWithPatterns(Client client, String... patterns) { - this.client = client; - client.psubscribe(patterns); - client.flush(); - process(client); - } - - public void proceed(Client client, String... channels) { - this.client = client; - client.subscribe(channels); - client.flush(); - process(client); - } - - private void process(Client client) { - - do { - List reply = client.getUnflushedObjectMultiBulkReply(); - final Object firstObj = reply.get(0); - if (!(firstObj instanceof byte[])) { - throw new JedisException("Unknown message type: " + firstObj); - } - final byte[] resp = (byte[]) firstObj; - if (Arrays.equals(SUBSCRIBE.getRaw(), resp)) { - subscribedChannels = ((Long) reply.get(2)).intValue(); - final byte[] bchannel = (byte[]) reply.get(1); - final String strchannel = (bchannel == null) ? null : SafeEncoder.encode(bchannel); - onSubscribe(strchannel, subscribedChannels); - } else if (Arrays.equals(UNSUBSCRIBE.getRaw(), resp)) { - subscribedChannels = ((Long) reply.get(2)).intValue(); - final byte[] bchannel = (byte[]) reply.get(1); - final String strchannel = (bchannel == null) ? null : SafeEncoder.encode(bchannel); - onUnsubscribe(strchannel, subscribedChannels); - } else if (Arrays.equals(MESSAGE.getRaw(), resp)) { - final byte[] bchannel = (byte[]) reply.get(1); - final byte[] bmesg = (byte[]) reply.get(2); - final String strchannel = (bchannel == null) ? null : SafeEncoder.encode(bchannel); - final String strmesg = (bmesg == null) ? null : SafeEncoder.encode(bmesg); - onMessage(strchannel, strmesg); - } else if (Arrays.equals(PMESSAGE.getRaw(), resp)) { - final byte[] bpattern = (byte[]) reply.get(1); - final byte[] bchannel = (byte[]) reply.get(2); - final byte[] bmesg = (byte[]) reply.get(3); - final String strpattern = (bpattern == null) ? null : SafeEncoder.encode(bpattern); - final String strchannel = (bchannel == null) ? null : SafeEncoder.encode(bchannel); - final String strmesg = (bmesg == null) ? null : SafeEncoder.encode(bmesg); - onPMessage(strpattern, strchannel, strmesg); - } else if (Arrays.equals(PSUBSCRIBE.getRaw(), resp)) { - subscribedChannels = ((Long) reply.get(2)).intValue(); - final byte[] bpattern = (byte[]) reply.get(1); - final String strpattern = (bpattern == null) ? null : SafeEncoder.encode(bpattern); - onPSubscribe(strpattern, subscribedChannels); - } else if (Arrays.equals(PUNSUBSCRIBE.getRaw(), resp)) { - subscribedChannels = ((Long) reply.get(2)).intValue(); - final byte[] bpattern = (byte[]) reply.get(1); - final String strpattern = (bpattern == null) ? null : SafeEncoder.encode(bpattern); - onPUnsubscribe(strpattern, subscribedChannels); - } else if (Arrays.equals(PONG.getRaw(), resp)) { - final byte[] bpattern = (byte[]) reply.get(1); - final String strpattern = (bpattern == null) ? null : SafeEncoder.encode(bpattern); - onPong(strpattern); - } else { - throw new JedisException("Unknown message type: " + firstObj); - } - } while (isSubscribed()); - - /* Invalidate instance since this thread is no longer listening */ - this.client = null; - } - - public int getSubscribedChannels() { - return subscribedChannels; - } + public void onUnsubscribe(String channel, int subscribedChannels) { + } + + public void onPUnsubscribe(String pattern, int subscribedChannels) { + } + + public void onPSubscribe(String pattern, int subscribedChannels) { + } + + public void onPong(String pattern) { + + } + + public void unsubscribe() { + if (client == null) { + throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); + } + client.unsubscribe(); + client.flush(); + } + + public void unsubscribe(String... channels) { + if (client == null) { + throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); + } + client.unsubscribe(channels); + client.flush(); + } + + public void subscribe(String... channels) { + if (client == null) { + throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); + } + client.subscribe(channels); + client.flush(); + } + + public void psubscribe(String... patterns) { + if (client == null) { + throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); + } + client.psubscribe(patterns); + client.flush(); + } + + public void punsubscribe() { + if (client == null) { + throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); + } + client.punsubscribe(); + client.flush(); + } + + public void punsubscribe(String... patterns) { + if (client == null) { + throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); + } + client.punsubscribe(patterns); + client.flush(); + } + + public void ping() { + if (client == null) { + throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); + } + client.ping(); + client.flush(); + } + + public boolean isSubscribed() { + return subscribedChannels > 0; + } + + public void proceedWithPatterns(Client client, String... patterns) { + this.client = client; + client.psubscribe(patterns); + client.flush(); + process(client); + } + + public void proceed(Client client, String... channels) { + this.client = client; + client.subscribe(channels); + client.flush(); + process(client); + } + + private void process(Client client) { + + do { + List reply = client.getUnflushedObjectMultiBulkReply(); + final Object firstObj = reply.get(0); + if (!(firstObj instanceof byte[])) { + throw new JedisException("Unknown message type: " + firstObj); + } + final byte[] resp = (byte[]) firstObj; + if (Arrays.equals(SUBSCRIBE.raw, resp)) { + subscribedChannels = ((Long) reply.get(2)).intValue(); + final byte[] bchannel = (byte[]) reply.get(1); + final String strchannel = (bchannel == null) ? null : SafeEncoder.encode(bchannel); + onSubscribe(strchannel, subscribedChannels); + } else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) { + subscribedChannels = ((Long) reply.get(2)).intValue(); + final byte[] bchannel = (byte[]) reply.get(1); + final String strchannel = (bchannel == null) ? null : SafeEncoder.encode(bchannel); + onUnsubscribe(strchannel, subscribedChannels); + } else if (Arrays.equals(MESSAGE.raw, resp)) { + final byte[] bchannel = (byte[]) reply.get(1); + final byte[] bmesg = (byte[]) reply.get(2); + final String strchannel = (bchannel == null) ? null : SafeEncoder.encode(bchannel); + final String strmesg = (bmesg == null) ? null : SafeEncoder.encode(bmesg); + onMessage(strchannel, strmesg); + } else if (Arrays.equals(PMESSAGE.raw, resp)) { + final byte[] bpattern = (byte[]) reply.get(1); + final byte[] bchannel = (byte[]) reply.get(2); + final byte[] bmesg = (byte[]) reply.get(3); + final String strpattern = (bpattern == null) ? null : SafeEncoder.encode(bpattern); + final String strchannel = (bchannel == null) ? null : SafeEncoder.encode(bchannel); + final String strmesg = (bmesg == null) ? null : SafeEncoder.encode(bmesg); + onPMessage(strpattern, strchannel, strmesg); + } else if (Arrays.equals(PSUBSCRIBE.raw, resp)) { + subscribedChannels = ((Long) reply.get(2)).intValue(); + final byte[] bpattern = (byte[]) reply.get(1); + final String strpattern = (bpattern == null) ? null : SafeEncoder.encode(bpattern); + onPSubscribe(strpattern, subscribedChannels); + } else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) { + subscribedChannels = ((Long) reply.get(2)).intValue(); + final byte[] bpattern = (byte[]) reply.get(1); + final String strpattern = (bpattern == null) ? null : SafeEncoder.encode(bpattern); + onPUnsubscribe(strpattern, subscribedChannels); + } else if (Arrays.equals(PONG.raw, resp)) { + final byte[] bpattern = (byte[]) reply.get(1); + final String strpattern = (bpattern == null) ? null : SafeEncoder.encode(bpattern); + onPong(strpattern); + } else { + throw new JedisException("Unknown message type: " + firstObj); + } + } while (isSubscribed()); + + /* Invalidate instance since this thread is no longer listening */ + this.client = null; + } + + public int getSubscribedChannels() { + return subscribedChannels; + } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisSentinelPool.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisSentinelPool.java index 9f5ecc395..944cfd245 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisSentinelPool.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisSentinelPool.java @@ -5,7 +5,6 @@ import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.stream.Collectors; import com.fr.third.org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.slf4j.Logger; @@ -16,198 +15,84 @@ import com.fr.third.redis.clients.jedis.exceptions.JedisException; public class JedisSentinelPool extends JedisPoolAbstract { - /** - * @deprecated This will be private in future. - */ - @Deprecated - protected static Logger log = LoggerFactory.getLogger(JedisSentinelPool.class); + protected GenericObjectPoolConfig poolConfig; - @Deprecated protected final GenericObjectPoolConfig poolConfig; - private final JedisFactory factory; + protected int connectionTimeout = Protocol.DEFAULT_TIMEOUT; + protected int soTimeout = Protocol.DEFAULT_TIMEOUT; - @Deprecated protected int connectionTimeout; - @Deprecated protected int soTimeout; - @Deprecated protected int infiniteSoTimeout; + protected String password; - @Deprecated protected String user; - @Deprecated protected String password; - @Deprecated protected int database; - @Deprecated protected String clientName; + protected int database = Protocol.DEFAULT_DATABASE; - @Deprecated protected int sentinelConnectionTimeout; - @Deprecated protected int sentinelSoTimeout; - @Deprecated protected String sentinelUser; - @Deprecated protected String sentinelPassword; - @Deprecated protected String sentinelClientName; + protected String clientName; - private final JedisClientConfig sentinelClientConfig; + protected Set masterListeners = new HashSet(); - /** - * WARNING: This variable will be changed to {@link java.util.Collection} in upcoming major release. - */ - protected final Set masterListeners = new HashSet<>(); + protected Logger log = LoggerFactory.getLogger(getClass().getName()); + private volatile JedisFactory factory; private volatile HostAndPort currentHostMaster; - - private final Object initPoolLock = new Object(); public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig) { + final GenericObjectPoolConfig poolConfig) { this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE); } public JedisSentinelPool(String masterName, Set sentinels) { - this(masterName, sentinels, new GenericObjectPoolConfig(), Protocol.DEFAULT_TIMEOUT, null, + this(masterName, sentinels, new GenericObjectPoolConfig(), Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE); } public JedisSentinelPool(String masterName, Set sentinels, String password) { - this(masterName, sentinels, new GenericObjectPoolConfig(), Protocol.DEFAULT_TIMEOUT, password); - } - - public JedisSentinelPool(String masterName, Set sentinels, String password, String sentinelPassword) { - this(masterName, sentinels, new GenericObjectPoolConfig(), Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, - password, Protocol.DEFAULT_DATABASE, null, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, sentinelPassword, null); + this(masterName, sentinels, new GenericObjectPoolConfig(), Protocol.DEFAULT_TIMEOUT, password); } public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, int timeout, final String password) { + final GenericObjectPoolConfig poolConfig, int timeout, final String password) { this(masterName, sentinels, poolConfig, timeout, password, Protocol.DEFAULT_DATABASE); } public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, final int timeout) { + final GenericObjectPoolConfig poolConfig, final int timeout) { this(masterName, sentinels, poolConfig, timeout, null, Protocol.DEFAULT_DATABASE); } public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, final String password) { + final GenericObjectPoolConfig poolConfig, final String password) { this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, password); } public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, int timeout, final String password, + final GenericObjectPoolConfig poolConfig, int timeout, final String password, final int database) { - this(masterName, sentinels, poolConfig, timeout, timeout, null, password, database); - } - - public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, int timeout, final String user, - final String password, final int database) { - this(masterName, sentinels, poolConfig, timeout, timeout, user, password, database); + this(masterName, sentinels, poolConfig, timeout, timeout, password, database); } public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, int timeout, final String password, + final GenericObjectPoolConfig poolConfig, int timeout, final String password, final int database, final String clientName) { this(masterName, sentinels, poolConfig, timeout, timeout, password, database, clientName); } public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, int timeout, final String user, - final String password, final int database, final String clientName) { - this(masterName, sentinels, poolConfig, timeout, timeout, user, password, database, clientName); - } - - public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, final int connectionTimeout, final int soTimeout, + final GenericObjectPoolConfig poolConfig, final int timeout, final int soTimeout, final String password, final int database) { - this(masterName, sentinels, poolConfig, connectionTimeout, soTimeout, null, password, database, null); + this(masterName, sentinels, poolConfig, timeout, soTimeout, password, database, null); } public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, final int connectionTimeout, final int soTimeout, - final String user, final String password, final int database) { - this(masterName, sentinels, poolConfig, connectionTimeout, soTimeout, user, password, database, null); - } - - public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, final int connectionTimeout, final int soTimeout, + final GenericObjectPoolConfig poolConfig, final int connectionTimeout, final int soTimeout, final String password, final int database, final String clientName) { - this(masterName, sentinels, poolConfig, connectionTimeout, soTimeout, null, password, database, clientName); - } - - public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, final int connectionTimeout, final int soTimeout, - final String user, final String password, final int database, final String clientName) { - this(masterName, sentinels, poolConfig, connectionTimeout, soTimeout, user, password, database, clientName, - Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null, null, null); - } - - public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, - final String user, final String password, final int database, final String clientName) { - this(masterName, sentinels, poolConfig, connectionTimeout, soTimeout, infiniteSoTimeout, user, password, database, clientName, - Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null, null, null); - } - - public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, final int connectionTimeout, final int soTimeout, - final String password, final int database, final String clientName, - final int sentinelConnectionTimeout, final int sentinelSoTimeout, final String sentinelPassword, - final String sentinelClientName) { - this(masterName, sentinels, poolConfig, connectionTimeout, soTimeout, null, password, database, clientName, - sentinelConnectionTimeout, sentinelSoTimeout, null, sentinelPassword, sentinelClientName); - } - - public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, final int connectionTimeout, final int soTimeout, - final String user, final String password, final int database, final String clientName, - final int sentinelConnectionTimeout, final int sentinelSoTimeout, final String sentinelUser, - final String sentinelPassword, final String sentinelClientName) { - this(masterName, sentinels, poolConfig, connectionTimeout, soTimeout, 0, user, password, database, clientName, - sentinelConnectionTimeout, sentinelSoTimeout, sentinelUser, sentinelPassword, sentinelClientName); - } - - public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, - final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, - final String user, final String password, final int database, final String clientName, - final int sentinelConnectionTimeout, final int sentinelSoTimeout, final String sentinelUser, - final String sentinelPassword, final String sentinelClientName) { - this(masterName, sentinels, poolConfig, new JedisFactory(connectionTimeout, soTimeout, infiniteSoTimeout, user, password, database, clientName)); + this.poolConfig = poolConfig; this.connectionTimeout = connectionTimeout; this.soTimeout = soTimeout; - this.infiniteSoTimeout = infiniteSoTimeout; - this.user = user; this.password = password; this.database = database; this.clientName = clientName; - this.sentinelConnectionTimeout = sentinelConnectionTimeout; - this.sentinelSoTimeout = sentinelSoTimeout; - this.sentinelUser = sentinelUser; - this.sentinelPassword = sentinelPassword; - this.sentinelClientName = sentinelClientName; - } - - public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, final JedisFactory factory) { - this(masterName, parseHostAndPorts(sentinels), poolConfig, factory, - DefaultJedisClientConfig.builder().build()); - } - - public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, final JedisClientConfig masteClientConfig, - final JedisClientConfig sentinelClientConfig) { - this(masterName, sentinels, poolConfig, new JedisFactory(masteClientConfig), sentinelClientConfig); - } - - public JedisSentinelPool(String masterName, Set sentinels, - final GenericObjectPoolConfig poolConfig, final JedisFactory factory, - final JedisClientConfig sentinelClientConfig) { - super(poolConfig, factory); - - this.poolConfig = poolConfig; - this.factory = factory; - this.sentinelClientConfig = sentinelClientConfig; HostAndPort master = initSentinels(sentinels, masterName); - initMaster(master); - } - - private static Set parseHostAndPorts(Set strings) { - return strings.stream().map(HostAndPort::parseString).collect(Collectors.toSet()); + initPool(master); } @Override @@ -223,32 +108,41 @@ public class JedisSentinelPool extends JedisPoolAbstract { return currentHostMaster; } - private void initMaster(HostAndPort master) { - synchronized (initPoolLock) { - if (!master.equals(currentHostMaster)) { - currentHostMaster = master; + private void initPool(HostAndPort master) { + if (!master.equals(currentHostMaster)) { + currentHostMaster = master; + if (factory == null) { + factory = new JedisFactory(master.getHost(), master.getPort(), connectionTimeout, + soTimeout, password, database, clientName); + initPool(poolConfig, factory); + } else { factory.setHostAndPort(currentHostMaster); - // although we clear the pool, we still have to check the returned object in getResource, - // this call only clears idle instances, not borrowed instances - clearInternalPool(); - - log.info("Created JedisSentinelPool to master at {}", master); + // although we clear the pool, we still have to check the + // returned object + // in getResource, this call only clears idle instances, not + // borrowed instances + internalPool.clear(); } + + log.info("Created JedisPool to master at " + master); } } - private HostAndPort initSentinels(Set sentinels, final String masterName) { + private HostAndPort initSentinels(Set sentinels, final String masterName) { HostAndPort master = null; boolean sentinelAvailable = false; log.info("Trying to find master from available Sentinels..."); - for (HostAndPort sentinel : sentinels) { + for (String sentinel : sentinels) { + final HostAndPort hap = HostAndPort.parseString(sentinel); - log.debug("Connecting to Sentinel {}", sentinel); + log.debug("Connecting to Sentinel {}", hap); - try (Jedis jedis = new Jedis(sentinel, sentinelClientConfig)) { + Jedis jedis = null; + try { + jedis = new Jedis(hap); List masterAddr = jedis.sentinelGetMasterAddrByName(masterName); @@ -256,7 +150,7 @@ public class JedisSentinelPool extends JedisPoolAbstract { sentinelAvailable = true; if (masterAddr == null || masterAddr.size() != 2) { - log.warn("Can not get master addr, master name: {}. Sentinel: {}", masterName, sentinel); + log.warn("Can not get master addr, master name: {}. Sentinel: {}", masterName, hap); continue; } @@ -267,14 +161,19 @@ public class JedisSentinelPool extends JedisPoolAbstract { // resolves #1036, it should handle JedisException there's another chance // of raising JedisDataException log.warn( - "Cannot get master address from sentinel running @ {}. Reason: {}. Trying next one.", - sentinel, e); + "Cannot get master address from sentinel running @ {}. Reason: {}. Trying next one.", hap, + e.toString()); + } finally { + if (jedis != null) { + jedis.close(); + } } } if (master == null) { if (sentinelAvailable) { - // can connect to sentinel, but master name seems to not monitored + // can connect to sentinel, but master name seems to not + // monitored throw new JedisException("Can connect to sentinel, but " + masterName + " seems to be not monitored..."); } else { @@ -283,11 +182,11 @@ public class JedisSentinelPool extends JedisPoolAbstract { } } - log.info("Redis master running at {}, starting Sentinel listeners...", master); + log.info("Redis master running at " + master + ", starting Sentinel listeners..."); - for (HostAndPort sentinel : sentinels) { - - MasterListener masterListener = new MasterListener(masterName, sentinel.getHost(), sentinel.getPort()); + for (String sentinel : sentinels) { + final HostAndPort hap = HostAndPort.parseString(sentinel); + MasterListener masterListener = new MasterListener(masterName, hap.getHost(), hap.getPort()); // whether MasterListener threads are alive or not, process can be stopped masterListener.setDaemon(true); masterListeners.add(masterListener); @@ -325,15 +224,17 @@ public class JedisSentinelPool extends JedisPoolAbstract { } @Override - public void returnResource(final Jedis resource) { + protected void returnBrokenResource(final Jedis resource) { if (resource != null) { - try { - resource.resetState(); - returnResourceObject(resource); - } catch (Exception e) { - returnBrokenResource(resource); - log.debug("Resource is returned to the pool as broken", e); - } + returnBrokenResourceObject(resource); + } + } + + @Override + protected void returnResource(final Jedis resource) { + if (resource != null) { + resource.resetState(); + returnResourceObject(resource); } } @@ -369,35 +270,35 @@ public class JedisSentinelPool extends JedisPoolAbstract { while (running.get()) { + j = new Jedis(host, port); + try { // double check that it is not being shutdown if (!running.get()) { break; } - final HostAndPort hostPort = new HostAndPort(host, port); - j = new Jedis(hostPort, sentinelClientConfig); - - // code for active refresh - List masterAddr = j.sentinelGetMasterAddrByName(masterName); + /* + * Added code for active refresh + */ + List masterAddr = j.sentinelGetMasterAddrByName(masterName); if (masterAddr == null || masterAddr.size() != 2) { - log.warn("Can not get master addr, master name: {}. Sentinel: {}.", masterName, - hostPort); - } else { - initMaster(toHostAndPort(masterAddr)); + log.warn("Can not get master addr, master name: {}. Sentinel: {}:{}.",masterName,host,port); + }else{ + initPool(toHostAndPort(masterAddr)); } j.subscribe(new JedisPubSub() { @Override public void onMessage(String channel, String message) { - log.debug("Sentinel {} published: {}.", hostPort, message); + log.debug("Sentinel {}:{} published: {}.", host, port, message); String[] switchMasterMsg = message.split(" "); if (switchMasterMsg.length > 3) { if (masterName.equals(switchMasterMsg[0])) { - initMaster(toHostAndPort(Arrays.asList(switchMasterMsg[3], switchMasterMsg[4]))); + initPool(toHostAndPort(Arrays.asList(switchMasterMsg[3], switchMasterMsg[4]))); } else { log.debug( "Ignoring message on +switch-master for master name {}, our master name is {}", @@ -405,8 +306,9 @@ public class JedisSentinelPool extends JedisPoolAbstract { } } else { - log.error("Invalid message received on Sentinel {} on channel +switch-master: {}", - hostPort, message); + log.error( + "Invalid message received on Sentinel {}:{} on channel +switch-master: {}", host, + port, message); } } }, "+switch-master"); @@ -425,9 +327,7 @@ public class JedisSentinelPool extends JedisPoolAbstract { log.debug("Unsubscribing from Sentinel at {}:{}", host, port); } } finally { - if (j != null) { - j.close(); - } + j.close(); } } } @@ -438,11 +338,11 @@ public class JedisSentinelPool extends JedisPoolAbstract { running.set(false); // This isn't good, the Jedis object is not thread safe if (j != null) { - j.close(); + j.disconnect(); } } catch (Exception e) { log.error("Caught exception while shutting down: ", e); } } } -} +} \ No newline at end of file diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisShardInfo.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisShardInfo.java index 2e5ff144d..824243061 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisShardInfo.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisShardInfo.java @@ -17,7 +17,6 @@ public class JedisShardInfo extends ShardInfo { private int soTimeout; private String host; private int port; - private String user = null; private String password = null; private String name = null; // Default Redis DB @@ -26,14 +25,13 @@ public class JedisShardInfo extends ShardInfo { 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); @@ -81,11 +79,9 @@ public class JedisShardInfo extends ShardInfo { 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, 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) { @@ -157,11 +153,10 @@ public class JedisShardInfo extends ShardInfo { this.name = name; } - public JedisShardInfo(String host, String name, int port, int timeout, int weight, boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, + 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(host, port, timeout, timeout, weight, ssl, sslSocketFactory, sslParameters, hostnameVerifier); this.name = name; } @@ -174,7 +169,6 @@ public class JedisShardInfo extends ShardInfo { 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); @@ -209,14 +203,6 @@ public class JedisShardInfo extends ShardInfo { this.password = auth; } - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - public int getConnectionTimeout() { return connectionTimeout; } @@ -243,7 +229,7 @@ public class JedisShardInfo extends ShardInfo { } public boolean getSsl() { - return ssl; + return ssl; } public SSLSocketFactory getSslSocketFactory() { @@ -262,5 +248,5 @@ public class JedisShardInfo extends ShardInfo { public Jedis createResource() { return new Jedis(this); } - + } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisSlotBasedConnectionHandler.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisSlotBasedConnectionHandler.java index 1bf7566a7..3873bd199 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisSlotBasedConnectionHandler.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisSlotBasedConnectionHandler.java @@ -2,9 +2,6 @@ package com.fr.third.redis.clients.jedis; import java.util.List; import java.util.Set; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLParameters; -import javax.net.ssl.SSLSocketFactory; import com.fr.third.org.apache.commons.pool2.impl.GenericObjectPoolConfig; @@ -14,72 +11,23 @@ import com.fr.third.redis.clients.jedis.exceptions.JedisNoReachableClusterNodeEx public class JedisSlotBasedConnectionHandler extends JedisClusterConnectionHandler { public JedisSlotBasedConnectionHandler(Set nodes, - final GenericObjectPoolConfig poolConfig, int timeout) { + 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); + final GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout) { + super(nodes, poolConfig, connectionTimeout, soTimeout, null); } - public JedisSlotBasedConnectionHandler(Set nodes, - GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, - String password) { + 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) { + 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, int connectionTimeout, int soTimeout, - String password, String clientName, boolean ssl, SSLSocketFactory sslSocketFactory, - SSLParameters sslParameters, HostnameVerifier hostnameVerifier, - JedisClusterHostAndPortMap portMap) { - super(nodes, poolConfig, connectionTimeout, soTimeout, password, clientName, ssl, - sslSocketFactory, sslParameters, hostnameVerifier, portMap); - } - - public JedisSlotBasedConnectionHandler(Set nodes, - GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, String user, - String password, String clientName, boolean ssl, SSLSocketFactory sslSocketFactory, - SSLParameters sslParameters, HostnameVerifier hostnameVerifier, - JedisClusterHostAndPortMap portMap) { - super(nodes, poolConfig, connectionTimeout, soTimeout, user, password, clientName, ssl, - sslSocketFactory, sslParameters, hostnameVerifier, portMap); - } - - public JedisSlotBasedConnectionHandler(Set nodes, - GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, - int infiniteSoTimeout, String user, String password, String clientName, boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier, JedisClusterHostAndPortMap portMap) { - super(nodes, poolConfig, connectionTimeout, soTimeout, infiniteSoTimeout, user, password, - clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier, portMap); - } - - public JedisSlotBasedConnectionHandler(Set nodes, - GenericObjectPoolConfig poolConfig, JedisClientConfig clientConfig) { - super(nodes, poolConfig, clientConfig); - } - @Override public Jedis getConnection() { // In antirez's redis-rb-cluster implementation, @@ -89,7 +37,6 @@ public class JedisSlotBasedConnectionHandler extends JedisClusterConnectionHandl List pools = cache.getShuffledNodesPool(); - JedisException suppressed = null; for (JedisPool pool : pools) { Jedis jedis = null; try { @@ -99,43 +46,35 @@ public class JedisSlotBasedConnectionHandler extends JedisClusterConnectionHandl continue; } - if (jedis.ping().equalsIgnoreCase("pong")) { - return jedis; - } + String result = jedis.ping(); + + if (result.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; + throw new JedisNoReachableClusterNodeException("No reachable node in cluster"); } @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 + // 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(); + renewSlotCache(); //It's abnormal situation for cluster mode, that we have just nothing for slot, try to rediscover state connectionPool = cache.getSlotPool(slot); if (connectionPool != null) { return connectionPool.getResource(); } else { - // no choice, fallback to new connection to random node + //no choice, fallback to new connection to random node return getConnection(); } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisSocketFactory.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisSocketFactory.java deleted file mode 100644 index 88194e8a9..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisSocketFactory.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.fr.third.redis.clients.jedis; - -import java.io.IOException; -import java.net.Socket; -import com.fr.third.redis.clients.jedis.exceptions.JedisConnectionException; - -/** - * JedisSocketFactory: responsible for creating socket connections - * from the within the Jedis client, the default socket factory will - * create TCP sockets with the recommended configuration. - *

      - * You can use a custom JedisSocketFactory for many use cases, such as: - * - a custom address resolver - * - a unix domain socket - * - a custom configuration for you TCP sockets - */ -public interface JedisSocketFactory { - - /** - * WARNING: Throwing IOException will not be supported in future. - * @return Socket - * @throws IOException this will be removed in future - * @throws JedisConnectionException - */ - Socket createSocket() throws IOException, 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/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Module.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Module.java index 3e75ea2c9..1d6e5e5c3 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Module.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Module.java @@ -1,7 +1,6 @@ package com.fr.third.redis.clients.jedis; public class Module { - private String name; private int version; @@ -10,6 +9,7 @@ public class Module { this.version = version; } + public String getName() { return name; } @@ -20,9 +20,8 @@ public class Module { @Override public boolean equals(Object o) { - if (o == null) return false; - if (o == this) return true; - if (!(o instanceof Module)) return false; + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; Module module = (Module) o; @@ -38,4 +37,5 @@ public class Module { return result; } -} + +} \ No newline at end of file diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/MultiKeyPipelineBase.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/MultiKeyPipelineBase.java index 353a0344a..414ef5a89 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/MultiKeyPipelineBase.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/MultiKeyPipelineBase.java @@ -1,9 +1,6 @@ package com.fr.third.redis.clients.jedis; -import com.fr.third.redis.clients.jedis.args.*; import com.fr.third.redis.clients.jedis.commands.*; -import com.fr.third.redis.clients.jedis.params.*; -import com.fr.third.redis.clients.jedis.resps.*; import java.util.List; import java.util.Map; @@ -16,55 +13,14 @@ public abstract class MultiKeyPipelineBase extends PipelineBase implements 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); + public Response> brpop(String... args) { + client.brpop(args); + return getResponse(BuilderFactory.STRING_LIST); } - @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); + public Response> brpop(int timeout, String... keys) { + client.brpop(timeout, keys); + return getResponse(BuilderFactory.STRING_LIST); } @Override @@ -73,114 +29,41 @@ public abstract class MultiKeyPipelineBase extends PipelineBase implements 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) { + public Response> brpop(int timeout, byte[]... 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); + public Response> blpop(byte[]... args) { + client.blpop(args); 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); + public Response> blpop(int timeout, byte[]... keys) { + client.blpop(timeout, keys); + return getResponse(BuilderFactory.STRING_LIST); } @Override @@ -423,72 +306,6 @@ public abstract class MultiKeyPipelineBase extends PipelineBase implements return getResponse(BuilderFactory.STRING); } - @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); @@ -513,30 +330,6 @@ public abstract class MultiKeyPipelineBase extends PipelineBase implements 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); @@ -651,18 +444,6 @@ public abstract class MultiKeyPipelineBase extends PipelineBase implements 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(); @@ -787,7 +568,7 @@ public abstract class MultiKeyPipelineBase extends PipelineBase implements @Override public Response eval(String script, int keyCount, String... params) { getClient(script).eval(script, keyCount, params); - return getResponse(BuilderFactory.ENCODED_OBJECT); + return getResponse(BuilderFactory.EVAL_RESULT); } @Override @@ -804,7 +585,7 @@ public abstract class MultiKeyPipelineBase extends PipelineBase implements @Override public Response evalsha(String sha1, int keyCount, String... params) { getClient(sha1).evalsha(sha1, keyCount, params); - return getResponse(BuilderFactory.ENCODED_OBJECT); + return getResponse(BuilderFactory.EVAL_RESULT); } @Override @@ -815,7 +596,7 @@ public abstract class MultiKeyPipelineBase extends PipelineBase implements @Override public Response eval(byte[] script, byte[] keyCount, byte[]... params) { getClient(script).eval(script, keyCount, params); - return getResponse(BuilderFactory.RAW_OBJECT); + return getResponse(BuilderFactory.EVAL_BINARY_RESULT); } @Override @@ -827,7 +608,7 @@ public abstract class MultiKeyPipelineBase extends PipelineBase implements @Override public Response eval(byte[] script, int keyCount, byte[]... params) { getClient(script).eval(script, keyCount, params); - return getResponse(BuilderFactory.RAW_OBJECT); + return getResponse(BuilderFactory.EVAL_BINARY_RESULT); } @Override @@ -844,7 +625,7 @@ public abstract class MultiKeyPipelineBase extends PipelineBase implements @Override public Response evalsha(byte[] sha1, int keyCount, byte[]... params) { getClient(sha1).evalsha(sha1, keyCount, params); - return getResponse(BuilderFactory.RAW_OBJECT); + return getResponse(BuilderFactory.EVAL_BINARY_RESULT); } @Override @@ -905,117 +686,7 @@ public abstract class MultiKeyPipelineBase extends PipelineBase implements 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); - } + } + + } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Pipeline.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Pipeline.java index d4c717c05..587fe91ed 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Pipeline.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Pipeline.java @@ -11,13 +11,13 @@ public class Pipeline extends MultiKeyPipelineBase implements Closeable { private MultiResponseBuilder currentMulti; private class MultiResponseBuilder extends Builder> { - private List> responses = new ArrayList<>(); + private List> responses = new ArrayList>(); @Override public List build(Object data) { @SuppressWarnings("unchecked") List list = (List) data; - List values = new ArrayList<>(); + List values = new ArrayList(); if (list.size() != responses.size()) { throw new JedisDataException("Expected data size " + responses.size() + " but was " @@ -54,7 +54,7 @@ public class Pipeline extends MultiKeyPipelineBase implements Closeable { if (currentMulti != null) { super.getResponse(BuilderFactory.STRING); // Expected QUEUED - Response lr = new Response<>(builder); + Response lr = new Response(builder); currentMulti.addResponse(lr); return lr; } else { @@ -111,7 +111,7 @@ public class Pipeline extends MultiKeyPipelineBase implements Closeable { public List syncAndReturnAll() { if (getPipelinedResponseLength() > 0) { List unformatted = client.getMany(getPipelinedResponseLength()); - List formatted = new ArrayList<>(); + List formatted = new ArrayList(); for (Object o : unformatted) { try { formatted.add(generateResponse(o).get()); diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/PipelineBase.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/PipelineBase.java index 3c3e53751..4462cd527 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/PipelineBase.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/PipelineBase.java @@ -5,20 +5,11 @@ import java.util.Map; import java.util.Set; import com.fr.third.redis.clients.jedis.commands.BinaryRedisPipeline; -import com.fr.third.redis.clients.jedis.commands.ProtocolCommand; import com.fr.third.redis.clients.jedis.commands.RedisPipeline; -import com.fr.third.redis.clients.jedis.params.GeoAddParams; import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; -import com.fr.third.redis.clients.jedis.params.GetExParams; -import com.fr.third.redis.clients.jedis.params.RestoreParams; import com.fr.third.redis.clients.jedis.params.SetParams; -import com.fr.third.redis.clients.jedis.params.XAddParams; -import com.fr.third.redis.clients.jedis.params.XClaimParams; -import com.fr.third.redis.clients.jedis.params.XPendingParams; -import com.fr.third.redis.clients.jedis.params.XTrimParams; import com.fr.third.redis.clients.jedis.params.ZAddParams; import com.fr.third.redis.clients.jedis.params.ZIncrByParams; -import com.fr.third.redis.clients.jedis.params.LPosParams; public abstract class PipelineBase extends Queable implements BinaryRedisPipeline, RedisPipeline { @@ -143,13 +134,13 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response expire(final String key, final long seconds) { + public Response expire(final String key, final int seconds) { getClient(key).expire(key, seconds); return getResponse(BuilderFactory.LONG); } @Override - public Response expire(final byte[] key, final long seconds) { + public Response expire(final byte[] key, final int seconds) { getClient(key).expire(key, seconds); return getResponse(BuilderFactory.LONG); } @@ -178,30 +169,6 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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); @@ -214,23 +181,19 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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); @@ -416,42 +379,6 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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); @@ -489,15 +416,13 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response linsert(final String key, final ListPosition where, final String pivot, - final String value) { + 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) { + 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); } @@ -526,56 +451,6 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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); @@ -684,18 +559,6 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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); @@ -756,13 +619,11 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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); @@ -781,13 +642,13 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response setex(final String key, final long seconds, final String value) { + public Response setex(final String key, final int 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) { + public Response setex(final byte[] key, final int seconds, final byte[] value) { getClient(key).setex(key, seconds, value); return getResponse(BuilderFactory.STRING); } @@ -822,24 +683,12 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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); @@ -906,7 +755,6 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin return getResponse(BuilderFactory.STRING); } - @Override public Response> srandmember(final String key, final int count) { getClient(key).srandmember(key, count); return getResponse(BuilderFactory.STRING_LIST); @@ -918,7 +766,6 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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); @@ -1003,8 +850,7 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response zadd(final String key, final double score, final String member, - final ZAddParams params) { + 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); } @@ -1016,8 +862,7 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response zadd(final String key, final Map scoreMembers, - final ZAddParams params) { + public Response zadd(final String key, final Map scoreMembers, final ZAddParams params) { getClient(key).zadd(key, scoreMembers, params); return getResponse(BuilderFactory.LONG); } @@ -1029,8 +874,7 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response zadd(final byte[] key, final double score, final byte[] member, - final ZAddParams params) { + 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); } @@ -1042,24 +886,11 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response zadd(final byte[] key, final Map scoreMembers, - final ZAddParams params) { + 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); @@ -1103,8 +934,7 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response zincrby(final String key, final double increment, final String member, - ZIncrByParams params) { + 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); } @@ -1116,8 +946,7 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response zincrby(final byte[] key, final double increment, final byte[] member, - ZIncrByParams params) { + public Response zincrby(final byte[] key, final double increment, final byte[] member, ZIncrByParams params) { getClient(key).zincrby(key, increment, member); return getResponse(BuilderFactory.DOUBLE); } @@ -1159,85 +988,79 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response> zrangeByScore(final String key, final double min, final double max, - final int offset, final int count) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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); } @@ -1267,85 +1090,81 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response> zrevrangeByScore(final String key, final double max, - final double min, final int offset, final int count) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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) { + 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); } @@ -1435,55 +1254,17 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response> zrevrangeWithScores(final String key, final long start, - final long stop) { + 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) { + 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); @@ -1502,72 +1283,12 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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); @@ -1668,80 +1389,56 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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) { + 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) { + public Response migrate(final byte[] 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); @@ -1766,89 +1463,51 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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) { + public Response restore(final String key, final int 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) { + public Response restore(final byte[] key, final int 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); @@ -1879,45 +1538,29 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response geoadd(final byte[] key, final double longitude, final double latitude, - final byte[] member) { + 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) { + 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) { + 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) { + 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); @@ -1925,8 +1568,7 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response geodist(final byte[] key, final byte[] member1, final byte[] member2, - final GeoUnit unit) { + 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); } @@ -1938,8 +1580,7 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response geodist(final String key, final String member1, final String member2, - final GeoUnit unit) { + 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); } @@ -1969,63 +1610,33 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin } @Override - public Response> georadius(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { + 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) { + 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) { + 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) { + 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) { @@ -2033,13 +1644,6 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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) { @@ -2047,13 +1651,6 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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) { @@ -2061,13 +1658,6 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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) { @@ -2075,13 +1665,6 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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); @@ -2094,18 +1677,6 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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); @@ -2118,297 +1689,4 @@ public abstract class PipelineBase extends Queable implements BinaryRedisPipelin 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); - } - - 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); - } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Protocol.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Protocol.java index 1c43addc8..31036953f 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Protocol.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Protocol.java @@ -1,5 +1,17 @@ package com.fr.third.redis.clients.jedis; +import com.fr.third.redis.clients.jedis.commands.ProtocolCommand; +import com.fr.third.redis.clients.jedis.exceptions.JedisAskDataException; +import com.fr.third.redis.clients.jedis.exceptions.JedisBusyException; +import com.fr.third.redis.clients.jedis.exceptions.JedisClusterException; +import com.fr.third.redis.clients.jedis.exceptions.JedisConnectionException; +import com.fr.third.redis.clients.jedis.exceptions.JedisDataException; +import com.fr.third.redis.clients.jedis.exceptions.JedisMovedDataException; +import com.fr.third.redis.clients.jedis.exceptions.JedisNoScriptException; +import com.fr.third.redis.clients.jedis.util.RedisInputStream; +import com.fr.third.redis.clients.jedis.util.RedisOutputStream; +import com.fr.third.redis.clients.jedis.util.SafeEncoder; + import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @@ -7,22 +19,13 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import com.fr.third.redis.clients.jedis.args.Rawable; -import com.fr.third.redis.clients.jedis.commands.ProtocolCommand; -import com.fr.third.redis.clients.jedis.exceptions.*; -import com.fr.third.redis.clients.jedis.util.RedisInputStream; -import com.fr.third.redis.clients.jedis.util.RedisOutputStream; -import com.fr.third.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 ASK_RESPONSE = "ASK"; + private static final String MOVED_RESPONSE = "MOVED"; + private static final String CLUSTERDOWN_RESPONSE = "CLUSTERDOWN"; + private static final String BUSY_RESPONSE = "BUSY"; + private static final String NOSCRIPT_RESPONSE = "NOSCRIPT"; public static final String DEFAULT_HOST = "localhost"; public static final int DEFAULT_PORT = 6379; @@ -74,9 +77,6 @@ public final class Protocol { public static final byte[] BYTES_TRUE = toByteArray(1); public static final byte[] BYTES_FALSE = toByteArray(0); - public static final byte[] BYTES_TILDE = SafeEncoder.encode("~"); - public static final byte[] BYTES_EQUAL = SafeEncoder.encode("="); - public static final byte[] BYTES_ASTERISK = SafeEncoder.encode("*"); public static final byte[] POSITIVE_INFINITY_BYTES = "+inf".getBytes(); public static final byte[] NEGATIVE_INFINITY_BYTES = "-inf".getBytes(); @@ -102,6 +102,7 @@ public final class Protocol { commandMappingSize = commandMapping.size(); } + private Protocol() { // this prevent the class from instantiation } @@ -145,24 +146,20 @@ public final class Protocol { String message = is.readLine(); // TODO: I'm not sure if this is the best way to do this. // Maybe Read only first 5 bytes instead? - if (message.startsWith(MOVED_PREFIX)) { + if (message.startsWith(MOVED_RESPONSE)) { String[] movedInfo = parseTargetHostAndSlot(message); throw new JedisMovedDataException(message, new HostAndPort(movedInfo[1], Integer.parseInt(movedInfo[2])), Integer.parseInt(movedInfo[0])); - } else if (message.startsWith(ASK_PREFIX)) { + } else if (message.startsWith(ASK_RESPONSE)) { String[] askInfo = parseTargetHostAndSlot(message); throw new JedisAskDataException(message, new HostAndPort(askInfo[1], Integer.parseInt(askInfo[2])), Integer.parseInt(askInfo[0])); - } else if (message.startsWith(CLUSTERDOWN_PREFIX)) { + } else if (message.startsWith(CLUSTERDOWN_RESPONSE)) { throw new JedisClusterException(message); - } else if (message.startsWith(BUSY_PREFIX)) { + } else if (message.startsWith(BUSY_RESPONSE)) { throw new JedisBusyException(message); - } else if (message.startsWith(NOSCRIPT_PREFIX)) { + } else if (message.startsWith(NOSCRIPT_RESPONSE) ) { throw new JedisNoScriptException(message); - } else if (message.startsWith(WRONGPASS_PREFIX)) { - throw new JedisAccessControlException(message); - } else if (message.startsWith(NOPERM_PREFIX)) { - throw new JedisAccessControlException(message); } throw new JedisDataException(message); } @@ -187,20 +184,20 @@ public final class Protocol { } private static Object process(final RedisInputStream is) { + final byte b = is.readByte(); - switch (b) { - case PLUS_BYTE: + if (b == PLUS_BYTE) { return processStatusCodeReply(is); - case DOLLAR_BYTE: + } else if (b == DOLLAR_BYTE) { return processBulkReply(is); - case ASTERISK_BYTE: + } else if (b == ASTERISK_BYTE) { return processMultiBulkReply(is); - case COLON_BYTE: + } else if (b == COLON_BYTE) { return processInteger(is); - case MINUS_BYTE: + } else if (b == MINUS_BYTE) { processError(is); return null; - default: + } else { throw new JedisConnectionException("Unknown reply: " + (char) b); } } @@ -240,7 +237,7 @@ public final class Protocol { if (num == -1) { return null; } - final List ret = new ArrayList<>(num); + final List ret = new ArrayList(num); for (int i = 0; i < num; i++) { try { ret.add(process(is)); @@ -278,25 +275,21 @@ public final class Protocol { } 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, @Deprecated SYNC, 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, 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, ACL, XINFO, - BITFIELD_RO, LPOS, SMISMEMBER, ZMSCORE, BZPOPMIN, BZPOPMAX, BLMOVE, LMOVE, COPY; + PING, SET, GET, 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, 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, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, + ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, + SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, + ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, ZLEXCOUNT, + ZRANGEBYLEX, ZREVRANGEBYLEX, ZREMRANGEBYLEX, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, + INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, 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, GEOADD, GEODIST, + GEOHASH, GEOPOS, GEORADIUS, GEORADIUSBYMEMBER, MODULE, BITFIELD, HSTRLEN, TOUCH, SWAPDB; private final byte[] raw; @@ -321,29 +314,12 @@ public final class Protocol { } } - 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, 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; - - /** - * @deprecated This will be private in future. Use {@link #getRaw()}. - */ - @Deprecated + public static enum Keyword { + 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, PING, PONG, UNLOAD; public final byte[] raw; Keyword() { raw = SafeEncoder.encode(this.name().toLowerCase(Locale.ENGLISH)); } - - @Override - public byte[] getRaw() { - return raw; - } } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Queable.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Queable.java index 188fe4cce..ee6a9014e 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Queable.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Queable.java @@ -4,7 +4,7 @@ import java.util.LinkedList; import java.util.Queue; public class Queable { - private Queue> pipelinedResponses = new LinkedList<>(); + private Queue> pipelinedResponses = new LinkedList>(); protected void clean() { pipelinedResponses.clear(); @@ -19,7 +19,7 @@ public class Queable { } protected Response getResponse(Builder builder) { - Response lr = new Response<>(builder); + Response lr = new Response(builder); pipelinedResponses.add(lr); return lr; } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ScanParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ScanParams.java index c09f0bf7f..7866b30e9 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ScanParams.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ScanParams.java @@ -17,10 +17,10 @@ import com.fr.third.redis.clients.jedis.util.SafeEncoder; public class ScanParams { - private final Map params = new EnumMap<>(Keyword.class); + private final Map params = new EnumMap(Keyword.class); - public static final String SCAN_POINTER_START = String.valueOf(0); - public static final byte[] SCAN_POINTER_START_BINARY = SafeEncoder.encode(SCAN_POINTER_START); + public final static String SCAN_POINTER_START = String.valueOf(0); + public final static byte[] SCAN_POINTER_START_BINARY = SafeEncoder.encode(SCAN_POINTER_START); public ScanParams match(final byte[] pattern) { params.put(MATCH, ByteBuffer.wrap(pattern)); @@ -29,9 +29,6 @@ public class ScanParams { /** * @see MATCH option in Redis documentation - * - * @param pattern - * @return */ public ScanParams match(final String pattern) { params.put(MATCH, ByteBuffer.wrap(SafeEncoder.encode(pattern))); @@ -40,9 +37,6 @@ public class ScanParams { /** * @see COUNT option in Redis documentation - * - * @param count - * @return */ public ScanParams count(final Integer count) { params.put(COUNT, ByteBuffer.wrap(Protocol.toByteArray(count))); @@ -50,7 +44,7 @@ public class ScanParams { } public Collection getParams() { - List paramsList = new ArrayList<>(params.size()); + List paramsList = new ArrayList(params.size()); for (Map.Entry param : params.entrySet()) { paramsList.add(param.getKey().raw); paramsList.add(param.getValue().array()); diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ScanResult.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ScanResult.java index 568371400..c9bce584b 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ScanResult.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ScanResult.java @@ -27,6 +27,7 @@ public class ScanResult { /** * Is the iteration complete. I.e. was the complete dataset scanned. + * * @return true if the iteration is complete */ public boolean isCompleteIteration() { diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ShardedJedis.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ShardedJedis.java index 37919745c..4160edeef 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ShardedJedis.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ShardedJedis.java @@ -8,20 +8,10 @@ import java.util.Set; import java.util.regex.Pattern; import com.fr.third.redis.clients.jedis.commands.JedisCommands; -import com.fr.third.redis.clients.jedis.commands.ProtocolCommand; -import com.fr.third.redis.clients.jedis.params.GeoAddParams; import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; -import com.fr.third.redis.clients.jedis.params.GetExParams; -import com.fr.third.redis.clients.jedis.params.RestoreParams; import com.fr.third.redis.clients.jedis.params.SetParams; -import com.fr.third.redis.clients.jedis.params.XAddParams; -import com.fr.third.redis.clients.jedis.params.XClaimParams; -import com.fr.third.redis.clients.jedis.params.XPendingParams; -import com.fr.third.redis.clients.jedis.params.XTrimParams; import com.fr.third.redis.clients.jedis.params.ZAddParams; import com.fr.third.redis.clients.jedis.params.ZIncrByParams; -import com.fr.third.redis.clients.jedis.params.LPosParams; -import com.fr.third.redis.clients.jedis.resps.KeyedListElement; import com.fr.third.redis.clients.jedis.util.Hashing; public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, Closeable { @@ -62,18 +52,6 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C 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); @@ -99,26 +77,13 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C } @Override - public String restore(final String key, final long ttl, final byte[] serializedValue) { + public String restore(final String key, final int 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) { + public Long expire(final String key, final int seconds) { Jedis j = getShard(key); return j.expire(key, seconds); } @@ -196,7 +161,7 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C } @Override - public String setex(final String key, final long seconds, final String value) { + public String setex(final String key, final int seconds, final String value) { Jedis j = getShard(key); return j.setex(key, seconds, value); } @@ -207,26 +172,24 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C 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); + public List blpop(final String arg) { + Jedis j = getShard(arg); + return j.blpop(arg); } @Override - public KeyedListElement blpop(final double timeout, final String key) { + public List blpop(final int 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); + public List brpop(final String arg) { + Jedis j = getShard(arg); + return j.brpop(arg); } @Override - public KeyedListElement brpop(final double timeout, final String key) { + public List brpop(final int timeout, final String key) { Jedis j = getShard(key); return j.brpop(timeout, key); } @@ -369,24 +332,6 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C 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); @@ -471,43 +416,12 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C 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); @@ -550,12 +464,6 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C 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); @@ -575,8 +483,7 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C } @Override - public Long zadd(final String key, final double score, final String member, - final ZAddParams params) { + 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); } @@ -593,12 +500,6 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C 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); @@ -618,8 +519,7 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C } @Override - public Double zincrby(final String key, final double increment, final String member, - ZIncrByParams params) { + 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); } @@ -654,24 +554,6 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C 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); @@ -684,36 +566,6 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C 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); @@ -751,15 +603,13 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C } @Override - public Set zrangeByScore(final String key, final double min, final double max, - final int offset, final int count) { + 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) { + 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); } @@ -777,15 +627,15 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C } @Override - public Set zrangeByScoreWithScores(final String key, final double min, final double max, - final int offset, final int count) { + 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) { + 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); } @@ -803,15 +653,13 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C } @Override - public Set zrangeByScore(final String key, final String min, final String max, - final int offset, final int count) { + 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) { + 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); } @@ -829,15 +677,15 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C } @Override - public Set zrangeByScoreWithScores(final String key, final String min, final String max, - final int offset, final int count) { + 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) { + 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); } @@ -882,8 +730,7 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C } @Override - public Set zrevrangeByLex(final String key, final String max, final String min, - final int offset, final int count) { + 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); } @@ -893,8 +740,7 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C } @Override - public Long linsert(final String key, final ListPosition where, final String pivot, - final String value) { + 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); } @@ -930,8 +776,7 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C } @Override - public ScanResult> hscan(final String key, final String cursor, - final ScanParams params) { + public ScanResult> hscan(final String key, final String cursor, final ScanParams params) { Jedis j = getShard(key); return j.hscan(key, cursor, params); } @@ -966,17 +811,16 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C boolean broken = false; for (Jedis jedis : getAllShards()) { - if (jedis.isBroken()) { + if (jedis.getClient().isBroken()) { broken = true; break; } } - ShardedJedisPool pool = this.dataSource; - this.dataSource = null; + if (broken) { - pool.returnBrokenResource(this); + dataSource.returnBrokenResource(this); } else { - pool.returnResource(this); + dataSource.returnResource(this); } } else { @@ -1013,8 +857,7 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C } @Override - public Long geoadd(final String key, final double longitude, final double latitude, - final String member) { + 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); } @@ -1025,12 +868,6 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C 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); @@ -1038,8 +875,7 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C } @Override - public Double geodist(final String key, final String member1, final String member2, - final GeoUnit unit) { + 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); } @@ -1057,247 +893,42 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C } @Override - public List georadius(final String key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { + 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) { + 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) { + 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) { + 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 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 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); - } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ShardedJedisPipeline.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ShardedJedisPipeline.java index f92a8043a..a94ba69b9 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ShardedJedisPipeline.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ShardedJedisPipeline.java @@ -5,15 +5,10 @@ import java.util.LinkedList; import java.util.List; import java.util.Queue; -/** - * @deprecated The support of {@link ShardedJedisPipeline} will be removed in next major release, - * due to several bugs and implementation issue. - */ -@Deprecated public class ShardedJedisPipeline extends PipelineBase { private BinaryShardedJedis jedis; - private List results = new ArrayList<>(); - private Queue clients = new LinkedList<>(); + private List results = new ArrayList(); + private Queue clients = new LinkedList(); private static class FutureResult { private Client client; @@ -32,7 +27,7 @@ public class ShardedJedisPipeline extends PipelineBase { } public List getResults() { - List r = new ArrayList<>(); + List r = new ArrayList(); for (FutureResult fr : results) { r.add(fr.get()); } @@ -40,7 +35,7 @@ public class ShardedJedisPipeline extends PipelineBase { } /** - * Synchronize pipeline by reading all responses. This operation closes the pipeline. In order to + * Syncronize pipeline by reading all responses. This operation closes the pipeline. In order to * get return values from pipelined commands, capture the different Response<?> of the * commands you execute. */ @@ -51,13 +46,13 @@ public class ShardedJedisPipeline extends PipelineBase { } /** - * Synchronize pipeline by reading all responses. This operation closes the pipeline. Whenever + * Syncronize pipeline by reading all responses. This operation closes the pipeline. Whenever * possible try to avoid using this version and use ShardedJedisPipeline.sync() as it won't go * through all the responses and generate the right response type (usually it is a waste of time). * @return A list of all the responses in the order you executed them. */ public List syncAndReturnAll() { - List formatted = new ArrayList<>(); + List formatted = new ArrayList(); for (Client client : clients) { formatted.add(generateResponse(client.getOne()).get()); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ShardedJedisPool.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ShardedJedisPool.java index 38b7ccb5f..cbc7b0214 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ShardedJedisPool.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ShardedJedisPool.java @@ -7,33 +7,27 @@ import com.fr.third.org.apache.commons.pool2.PooledObject; import com.fr.third.org.apache.commons.pool2.PooledObjectFactory; import com.fr.third.org.apache.commons.pool2.impl.DefaultPooledObject; import com.fr.third.org.apache.commons.pool2.impl.GenericObjectPoolConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.fr.third.redis.clients.jedis.util.Hashing; import com.fr.third.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) { + public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, List shards) { this(poolConfig, shards, Hashing.MURMUR_HASH); } - public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, - List shards, Hashing algo) { + public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, List shards, + Hashing algo) { this(poolConfig, shards, algo, null); } - public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, - List shards, Pattern keyTagPattern) { + 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) { + public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, List shards, + Hashing algo, Pattern keyTagPattern) { super(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern)); } @@ -45,7 +39,14 @@ public class ShardedJedisPool extends Pool { } @Override - public void returnResource(final ShardedJedis resource) { + protected void returnBrokenResource(final ShardedJedis resource) { + if (resource != null) { + returnBrokenResourceObject(resource); + } + } + + @Override + protected void returnResource(final ShardedJedis resource) { if (resource != null) { resource.resetState(); returnResourceObject(resource); @@ -56,10 +57,9 @@ public class ShardedJedisPool extends Pool { * PoolableObjectFactory custom impl. */ private static class ShardedJedisFactory implements PooledObjectFactory { - - private final List shards; - private final Hashing algo; - private final Pattern keyTagPattern; + private List shards; + private Hashing algo; + private Pattern keyTagPattern; public ShardedJedisFactory(List shards, Hashing algo, Pattern keyTagPattern) { this.shards = shards; @@ -70,7 +70,7 @@ public class ShardedJedisPool extends Pool { @Override public PooledObject makeObject() throws Exception { ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern); - return new DefaultPooledObject<>(jedis); + return new DefaultPooledObject(jedis); } @Override @@ -79,17 +79,14 @@ public class ShardedJedisPool extends Pool { for (Jedis jedis : shardedJedis.getAllShards()) { if (jedis.isConnected()) { try { - // need a proper test, probably with mock - if (!jedis.isBroken()) { + try { jedis.quit(); + } catch (Exception e) { + } - } catch (Exception e) { - logger.warn("Error while QUIT", e); - } - try { jedis.disconnect(); } catch (Exception e) { - logger.warn("Error while disconnect", e); + } } } @@ -120,4 +117,4 @@ public class ShardedJedisPool extends Pool { } } -} +} \ No newline at end of file diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/SortingParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/SortingParams.java index efae9b3f4..178ff7190 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/SortingParams.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/SortingParams.java @@ -19,7 +19,7 @@ import com.fr.third.redis.clients.jedis.util.SafeEncoder; * Builder Class for {@link Jedis#sort(String, SortingParams) SORT} Parameters. */ public class SortingParams { - private final List params = new ArrayList<>(); + private List params = new ArrayList(); /** * Sort by weight in keys. @@ -50,7 +50,7 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams by(final byte[] pattern) { - params.add(BY.getRaw()); + params.add(BY.raw); params.add(pattern); return this; } @@ -63,8 +63,8 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams nosort() { - params.add(BY.getRaw()); - params.add(NOSORT.getRaw()); + params.add(BY.raw); + params.add(NOSORT.raw); return this; } @@ -77,7 +77,7 @@ public class SortingParams { * @return the sortingParams Object */ public SortingParams desc() { - params.add(DESC.getRaw()); + params.add(DESC.raw); return this; } @@ -86,7 +86,7 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams asc() { - params.add(ASC.getRaw()); + params.add(ASC.raw); return this; } @@ -97,7 +97,7 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams limit(final int start, final int count) { - params.add(LIMIT.getRaw()); + params.add(LIMIT.raw); params.add(Protocol.toByteArray(start)); params.add(Protocol.toByteArray(count)); return this; @@ -109,7 +109,7 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams alpha() { - params.add(ALPHA.getRaw()); + params.add(ALPHA.raw); return this; } @@ -129,7 +129,7 @@ public class SortingParams { */ public SortingParams get(String... patterns) { for (final String pattern : patterns) { - params.add(GET.getRaw()); + params.add(GET.raw); params.add(SafeEncoder.encode(pattern)); } return this; @@ -151,7 +151,7 @@ public class SortingParams { */ public SortingParams get(byte[]... patterns) { for (final byte[] pattern : patterns) { - params.add(GET.getRaw()); + params.add(GET.raw); params.add(pattern); } return this; diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamConsumersInfo.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamConsumersInfo.java deleted file mode 100644 index df207f74b..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamConsumersInfo.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.fr.third.redis.clients.jedis; - -import java.util.Map; - -/** - * This class holds information about a consumer. They can be access via getters. For future purpose - * there is also {@link #getConsumerInfo()}} method that returns a generic {@code Map} - in case - * where more info is returned from the server. - */ -public class StreamConsumersInfo { - - public static final String NAME = "name"; - public static final String IDLE = "idle"; - public static final String PENDING = "pending"; - - private final String name; - private final long idle; - private final long pending; - private final Map consumerInfo; - - /** - * @param map contains key-value pairs with consumer info - */ - public StreamConsumersInfo(Map map) { - - consumerInfo = map; - name = (String) map.get(NAME); - idle = (long) map.get(IDLE); - pending = (long) map.get(PENDING); - - } - - public String getName() { - return name; - } - - public long getIdle() { - return idle; - } - - public long getPending() { - return pending; - } - - /** - * @return Generic map containing all key-value pairs returned by the server - */ - public Map getConsumerInfo() { - return consumerInfo; - } - -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamEntry.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamEntry.java deleted file mode 100644 index 9d7d26b53..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamEntry.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.fr.third.redis.clients.jedis; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Map; - -public class StreamEntry implements Serializable { - - private static final long serialVersionUID = 1L; - - private StreamEntryID id; - private Map fields; - - public StreamEntry(StreamEntryID id, Map fields) { - this.id = id; - this.fields = fields; - } - - public StreamEntryID getID() { - return id; - } - - public Map getFields() { - return fields; - } - - @Override - public String toString() { - return id + " " + fields; - } - - private void writeObject(java.io.ObjectOutputStream out) throws IOException { - out.writeUnshared(this.id); - out.writeUnshared(this.fields); - } - - private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { - this.id = (StreamEntryID) in.readUnshared(); - this.fields = (Map) in.readUnshared(); - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamEntryID.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamEntryID.java deleted file mode 100644 index 653be7d6e..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamEntryID.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.fr.third.redis.clients.jedis; - -import java.io.IOException; -import java.io.Serializable; - -public class StreamEntryID implements Comparable, Serializable { - - private static final long serialVersionUID = 1L; - - /** - * Should be used only with XADD - * - * - * XADD mystream * field1 value1 - * - */ - public static final StreamEntryID NEW_ENTRY = new StreamEntryID() { - - private static final long serialVersionUID = 1L; - - @Override - public String toString() { - return "*"; - } - }; - - /** - * Should be used only with XGROUP CREATE - * - * - * XGROUP CREATE mystream consumer-group-name $ - * - */ - public static final StreamEntryID LAST_ENTRY = new StreamEntryID() { - - private static final long serialVersionUID = 1L; - - @Override - public String toString() { - return "$"; - } - }; - - /** - * Should be used only with XREADGROUP - * - * XREADGROUP $GroupName $ConsumerName BLOCK 2000 COUNT 10 STREAMS mystream > - * - */ - public static final StreamEntryID UNRECEIVED_ENTRY = new StreamEntryID() { - - private static final long serialVersionUID = 1L; - - @Override - public String toString() { - return ">"; - } - }; - - private long time; - private long sequence; - - public StreamEntryID() { - this(0, 0L); - } - - public StreamEntryID(String id) { - String[] split = id.split("-"); - this.time = Long.parseLong(split[0]); - this.sequence = Long.parseLong(split[1]); - } - - public StreamEntryID(long time, long sequence) { - this.time = time; - this.sequence = sequence; - } - - @Override - public String toString() { - return time + "-" + sequence; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - StreamEntryID other = (StreamEntryID) obj; - return this.time == other.time && this.sequence == other.sequence; - } - - @Override - public int hashCode() { - return this.toString().hashCode(); - } - - @Override - public int compareTo(StreamEntryID other) { - int timeComapre = Long.compare(this.time, other.time); - return timeComapre != 0 ? timeComapre : Long.compare(this.sequence, other.sequence); - } - - public long getTime() { - return time; - } - - public long getSequence() { - return sequence; - } - - private void writeObject(java.io.ObjectOutputStream out) throws IOException { - out.writeLong(this.time); - out.writeLong(this.sequence); - } - - private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { - this.time = in.readLong(); - this.sequence = in.readLong(); - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamGroupInfo.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamGroupInfo.java deleted file mode 100644 index 2fbc663b6..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamGroupInfo.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.fr.third.redis.clients.jedis; - -import java.io.Serializable; -import java.util.Map; - -/** - * This class holds information about a stream group. They can be access via getters. For future - * purpose there is also {@link #getGroupInfo()} method that returns a generic {@code Map} - in case - * where more info is returned from the server. - */ -public class StreamGroupInfo implements Serializable { - - public static final String NAME = "name"; - public static final String CONSUMERS = "consumers"; - public static final String PENDING = "pending"; - public static final String LAST_DELIVERED = "last-delivered-id"; - - private final String name; - private final long consumers; - private final long pending; - private final StreamEntryID lastDeliveredId; - private final Map groupInfo; - - /** - * @param map contains key-value pairs with group info - */ - public StreamGroupInfo(Map map) { - - groupInfo = map; - name = (String) map.get(NAME); - consumers = (long) map.get(CONSUMERS); - pending = (long) map.get(PENDING); - lastDeliveredId = (StreamEntryID) map.get(LAST_DELIVERED); - - } - - public String getName() { - return name; - } - - public long getConsumers() { - return consumers; - } - - public long getPending() { - return pending; - } - - public StreamEntryID getLastDeliveredId() { - return lastDeliveredId; - } - - /** - * @return Generic map containing all key-value pairs returned by the server - */ - public Map getGroupInfo() { - return groupInfo; - } - -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamInfo.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamInfo.java deleted file mode 100644 index 274d8d4cd..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamInfo.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.fr.third.redis.clients.jedis; - -import java.io.Serializable; -import java.util.Map; - -/** - * This class holds information about stream. They can be access via getters. For future purpose - * there is also {@link #getStreamInfo} method that returns a generic {@code Map} - in case where - * more info is returned from the server. - */ - -public class StreamInfo implements Serializable { - - public static final String LENGTH = "length"; - public static final String RADIX_TREE_KEYS = "radix-tree-keys"; - public static final String RADIX_TREE_NODES = "radix-tree-nodes"; - public static final String GROUPS = "groups"; - public static final String LAST_GENERATED_ID = "last-generated-id"; - public static final String FIRST_ENTRY = "first-entry"; - public static final String LAST_ENTRY = "last-entry"; - - private final long length; - private final long radixTreeKeys; - private final long radixTreeNodes; - private final long groups; - private final StreamEntryID lastGeneratedId; - private final StreamEntry firstEntry; - private final StreamEntry lastEntry; - private final Map streamInfo; - - /** - * @param map contains key-value pairs with stream info - */ - public StreamInfo(Map map) { - - streamInfo = map; - length = (Long) map.get(LENGTH); - radixTreeKeys = (Long) map.get(RADIX_TREE_KEYS); - radixTreeNodes = (Long) map.get(RADIX_TREE_NODES); - groups = (Long) map.get(GROUPS); - lastGeneratedId = (StreamEntryID) map.get(LAST_GENERATED_ID); - firstEntry = (StreamEntry) map.get(FIRST_ENTRY); - lastEntry = (StreamEntry) map.get(LAST_ENTRY); - - } - - public long getLength() { - return length; - } - - public long getRadixTreeKeys() { - return radixTreeKeys; - } - - public long getRadixTreeNodes() { - return radixTreeNodes; - } - - public long getGroups() { - return groups; - } - - public StreamEntryID getLastGeneratedId() { - return lastGeneratedId; - } - - public StreamEntry getFirstEntry() { - return firstEntry; - } - - public StreamEntry getLastEntry() { - return lastEntry; - } - - /** - * @return Generic map containing all key-value pairs returned by the server - */ - public Map getStreamInfo() { - return streamInfo; - } - -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamPendingEntry.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamPendingEntry.java deleted file mode 100644 index 06388af4a..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamPendingEntry.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.fr.third.redis.clients.jedis; - -import java.io.IOException; -import java.io.Serializable; - -public class StreamPendingEntry implements Serializable { - - private static final long serialVersionUID = 1L; - - private StreamEntryID id; - private String consumerName; - private long idleTime; - private long deliveredTimes; - - public StreamPendingEntry(StreamEntryID id, String consumerName, long idleTime, - long deliveredTimes) { - this.id = id; - this.consumerName = consumerName; - this.idleTime = idleTime; - this.deliveredTimes = deliveredTimes; - } - - public StreamEntryID getID() { - return id; - } - - public long getIdleTime() { - return idleTime; - } - - public long getDeliveredTimes() { - return deliveredTimes; - } - - public String getConsumerName() { - return consumerName; - } - - @Override - public String toString() { - return this.id + " " + this.consumerName + " idle:" + this.idleTime + " times:" - + this.deliveredTimes; - } - - private void writeObject(java.io.ObjectOutputStream out) throws IOException { - out.writeUnshared(this.id); - out.writeUTF(this.consumerName); - out.writeLong(idleTime); - out.writeLong(this.deliveredTimes); - } - - private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { - this.id = (StreamEntryID) in.readUnshared(); - this.consumerName = in.readUTF(); - this.idleTime = in.readLong(); - this.deliveredTimes = in.readLong(); - } - -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamPendingSummary.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamPendingSummary.java deleted file mode 100644 index 0da70b3c3..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamPendingSummary.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.fr.third.redis.clients.jedis; - -import java.io.Serializable; -import java.util.Map; - -public class StreamPendingSummary implements Serializable { - - private static final long serialVersionUID = 1L; - - private final long total; - private final StreamEntryID minId; - private final StreamEntryID maxId; - private final Map consumerMessageCount; - - public StreamPendingSummary(long total, StreamEntryID minId, StreamEntryID maxId, - Map consumerMessageCount) { - this.total = total; - this.minId = minId; - this.maxId = maxId; - this.consumerMessageCount = consumerMessageCount; - } - - public long getTotal() { - return total; - } - - public StreamEntryID getMinId() { - return minId; - } - - public StreamEntryID getMaxId() { - return maxId; - } - - public Map getConsumerMessageCount() { - return consumerMessageCount; - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Transaction.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Transaction.java index fcad4b3cc..9aec64583 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Transaction.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Transaction.java @@ -47,7 +47,7 @@ public class Transaction extends MultiKeyPipelineBase implements Closeable { if (unformatted == null) { return null; } - List formatted = new ArrayList<>(); + List formatted = new ArrayList(); for (Object o : unformatted) { try { formatted.add(generateResponse(o).get()); @@ -68,7 +68,7 @@ public class Transaction extends MultiKeyPipelineBase implements Closeable { if (unformatted == null) { return null; } - List> response = new ArrayList<>(); + List> response = new ArrayList>(); for (Object o : unformatted) { response.add(generateResponse(o)); } @@ -91,30 +91,4 @@ public class Transaction extends MultiKeyPipelineBase implements Closeable { public void close() { clear(); } - - private static final String WATCH_INSIDE_MULTI_MESSAGE = "WATCH inside MULTI is not allowed"; - - /** - * @param keys - * @return - * @throws UnsupportedOperationException - * @deprecated {@value #WATCH_INSIDE_MULTI_MESSAGE} - */ - @Override - @Deprecated - public Response watch(String... keys) throws UnsupportedOperationException { - throw new UnsupportedOperationException(WATCH_INSIDE_MULTI_MESSAGE); - } - - /** - * @param keys - * @return - * @throws UnsupportedOperationException - * @deprecated {@value #WATCH_INSIDE_MULTI_MESSAGE} - */ - @Override - @Deprecated - public Response watch(byte[]... keys) throws UnsupportedOperationException { - throw new UnsupportedOperationException(WATCH_INSIDE_MULTI_MESSAGE); - } -} +} \ No newline at end of file diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Tuple.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Tuple.java index 7b722f6d3..be005e189 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Tuple.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Tuple.java @@ -1,7 +1,6 @@ package com.fr.third.redis.clients.jedis; import java.util.Arrays; -import java.util.Objects; import com.fr.third.redis.clients.jedis.util.ByteArrayComparator; import com.fr.third.redis.clients.jedis.util.SafeEncoder; @@ -37,13 +36,12 @@ public class Tuple implements Comparable { @Override public boolean equals(Object obj) { + if (this == obj) return true; if (obj == null) return false; - if (obj == this) return true; - if (!(obj instanceof Tuple)) return false; - + if (getClass() != obj.getClass()) return false; Tuple other = (Tuple) obj; if (!Arrays.equals(element, other.element)) return false; - return Objects.equals(score, other.score); + return equals(score, other.score); } @Override @@ -53,7 +51,7 @@ public class Tuple implements Comparable { public static int compare(Tuple t1, Tuple t2) { int compScore = Double.compare(t1.score, t2.score); - if (compScore != 0) return compScore; + if(compScore != 0) return compScore; return ByteArrayComparator.compare(t1.element, t2.element); } @@ -78,4 +76,8 @@ public class Tuple implements Comparable { public String toString() { return '[' + SafeEncoder.encode(element) + ',' + score + ']'; } + + public static boolean equals(Object a, Object b) { + return (a == b) || (a != null && a.equals(b)); + } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ZParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ZParams.java index 4e8fa4f9a..0817c3d7b 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ZParams.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ZParams.java @@ -14,30 +14,21 @@ public class ZParams { public enum Aggregate { SUM, MIN, MAX; - /** - * @deprecated This will be private in future. Use {@link #getRaw()}. - */ - @Deprecated public final byte[] raw; Aggregate() { raw = SafeEncoder.encode(name()); } - - public byte[] getRaw() { - return raw; - } } - private final List params = new ArrayList<>(); + private List params = new ArrayList(); /** * Set weights. * @param weights weights. - * @return */ public ZParams weights(final double... weights) { - params.add(WEIGHTS.getRaw()); + params.add(WEIGHTS.raw); for (final double weight : weights) { params.add(Protocol.toByteArray(weight)); } @@ -50,7 +41,7 @@ public class ZParams { } public ZParams aggregate(final Aggregate aggregate) { - params.add(AGGREGATE.getRaw()); + params.add(AGGREGATE.raw); params.add(aggregate.raw); return this; } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/FlushMode.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/FlushMode.java deleted file mode 100644 index 29ea7a2f6..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/FlushMode.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.fr.third.redis.clients.jedis.args; - -import com.fr.third.redis.clients.jedis.util.SafeEncoder; - -/** - * Enum object describing flushing mode. - */ -public enum FlushMode implements Rawable { - - /** - * flushes synchronously - */ - SYNC, - - /** - * flushes asynchronously - */ - ASYNC; - - private final byte[] raw; - - FlushMode() { - raw = SafeEncoder.encode(this.name()); - } - - @Override - public byte[] getRaw() { - return raw; - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/ListDirection.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/ListDirection.java deleted file mode 100644 index a7563b4c6..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/ListDirection.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.fr.third.redis.clients.jedis.args; - -import com.fr.third.redis.clients.jedis.util.SafeEncoder; - -/** - * 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()); - } - - @Override - public byte[] getRaw() { - return raw; - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/Rawable.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/Rawable.java deleted file mode 100644 index 5ccfcb840..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/Rawable.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.fr.third.redis.clients.jedis.args; - -public interface Rawable { - - byte[] getRaw(); -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/UnblockType.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/UnblockType.java deleted file mode 100644 index 30c1c4533..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/UnblockType.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.fr.third.redis.clients.jedis.args; - -import com.fr.third.redis.clients.jedis.util.SafeEncoder; - -/** - * Unblock type for {@code CLIENT UNBLOCK} command. - */ -public enum UnblockType implements Rawable { - TIMEOUT, ERROR; - - private final byte[] raw; - - UnblockType() { - raw = SafeEncoder.encode(this.name()); - } - - @Override - public byte[] getRaw() { - return raw; - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/package-info.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/package-info.java deleted file mode 100644 index c0982f972..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/* - * This package contains the classes that represent different Redis command arguments. - */ -package com.fr.third.redis.clients.jedis.args; diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/AdvancedBinaryJedisCommands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/AdvancedBinaryJedisCommands.java index 5ffeed32b..61751368b 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/AdvancedBinaryJedisCommands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/AdvancedBinaryJedisCommands.java @@ -2,11 +2,6 @@ package com.fr.third.redis.clients.jedis.commands; import java.util.List; -import com.fr.third.redis.clients.jedis.AccessControlUser; -import com.fr.third.redis.clients.jedis.args.UnblockType; -import com.fr.third.redis.clients.jedis.params.MigrateParams; -import com.fr.third.redis.clients.jedis.params.ClientKillParams; - public interface AdvancedBinaryJedisCommands { List configGet(byte[] pattern); @@ -17,78 +12,13 @@ public interface AdvancedBinaryJedisCommands { Long slowlogLen(); - List slowlogGetBinary(); + List slowlogGetBinary(); - List slowlogGetBinary(long entries); + 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); - - Long clientUnblock(long clientId, UnblockType unblockType); - - byte[] clientGetnameBinary(); - - byte[] clientListBinary(); - - byte[] clientListBinary(long... clientIds); - - byte[] clientInfoBinary(); - - String clientSetname(byte[] name); - - Long clientId(); - - byte[] memoryDoctorBinary(); - - Long memoryUsage(byte[] key); - - Long memoryUsage(byte[] key, int samples); - - 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/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/AdvancedJedisCommands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/AdvancedJedisCommands.java index c0c9f3938..29eedfba5 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/AdvancedJedisCommands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/AdvancedJedisCommands.java @@ -2,11 +2,6 @@ package com.fr.third.redis.clients.jedis.commands; import java.util.List; -import com.fr.third.redis.clients.jedis.AccessControlLogEntry; -import com.fr.third.redis.clients.jedis.AccessControlUser; -import com.fr.third.redis.clients.jedis.args.UnblockType; -import com.fr.third.redis.clients.jedis.params.MigrateParams; -import com.fr.third.redis.clients.jedis.params.ClientKillParams; import com.fr.third.redis.clients.jedis.util.Slowlog; public interface AdvancedJedisCommands { @@ -27,69 +22,4 @@ public interface AdvancedJedisCommands { 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(long... clientIds); - - String clientInfo(); - - String clientSetname(String name); - - Long clientId(); - - Long clientUnblock(long clientId, UnblockType unblockType); - - String memoryDoctor(); - - Long memoryUsage(String key); - - Long memoryUsage(String key, int samples); - - 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/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BasicCommands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BasicCommands.java index 1ee0552af..ecbab5632 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BasicCommands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BasicCommands.java @@ -1,41 +1,32 @@ package com.fr.third.redis.clients.jedis.commands; import com.fr.third.redis.clients.jedis.DebugParams; -import com.fr.third.redis.clients.jedis.args.FlushMode; public interface BasicCommands { /** * This command is often used to test if a connection is still alive, or to measure latency. + * * @return PONG */ String ping(); /** - * Ask the server to close the connection. The connection is closed as soon as all pending replies - * have been written to the client. + * Ask the server to close the connection. The connection is closed as soon as all pending replies have been written to the client. * @return OK */ String quit(); /** - * 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. + * 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. * @return OK */ 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. + * @return the number of key in the curr currently-selected database. */ Long dbSize(); @@ -62,63 +53,33 @@ public interface BasicCommands { String flushAll(); /** - * Delete all the keys of all the existing databases, not just the currently selected one. - * @param flushMode - * @return a simple string reply (OK) - */ - String flushAll(FlushMode flushMode); - - /** - * Request for authentication in a password-protected Redis server. Redis can be instructed to - * require a password before allowing clients to execute commands. This is done using the - * requirepass directive in the configuration file. If password matches the password in the - * configuration file, the server replies with the OK status code and starts accepting commands. - * Otherwise, an error is returned and the clients needs to try a new password. + * Request for authentication in a password-protected Redis server. Redis can be instructed to require a password before allowing clients to execute commands. This is done using the requirepass directive in the configuration file. + If password matches the password in the configuration file, the server replies with the OK status code and starts accepting commands. Otherwise, an error is returned and the clients needs to try a new password. * @param password * @return the result of the auth */ String auth(String password); /** - * Request for authentication with username and password, based on the ACL feature introduced in - * Redis 6.0 see https://redis.io/topics/acl - * @param user - * @param password - * @return - */ - String auth(String user, String password); - - /** - * The SAVE commands performs a synchronous save of the dataset producing a point in time snapshot - * of all the data inside the Redis instance, in the form of an RDB file. You almost never want to - * call SAVE in production environments where it will block all the other clients. Instead usually - * BGSAVE is used. However in case of issues preventing Redis to create the background saving - * child (for instance errors in the fork(2) system call), the SAVE command can be a good last - * resort to perform the dump of the latest dataset. + * The SAVE commands performs a synchronous save of the dataset producing a point in time snapshot of all the data inside the Redis instance, in the form of an RDB file. + You almost never want to call SAVE in production environments where it will block all the other clients. Instead usually BGSAVE is used. However in case of issues preventing Redis to create the background saving child (for instance errors in the fork(2) system call), the SAVE command can be a good last resort to perform the dump of the latest dataset. * @return result of the save */ String save(); /** - * Save the DB in background. The OK code is immediately returned. Redis forks, the parent - * continues to serve the clients, the child saves the DB on disk then exits. A client may be able - * to check if the operation succeeded using the LASTSAVE command. + * Save the DB in background. The OK code is immediately returned. Redis forks, the parent continues to serve the clients, the child saves the DB on disk then exits. A client may be able to check if the operation succeeded using the LASTSAVE command. * @return ok */ String bgsave(); /** - * Instruct Redis to start an Append Only File rewrite process. The rewrite will create a small - * optimized version of the current Append Only File If BGREWRITEAOF fails, no data gets lost as - * the old AOF will be untouched. The rewrite will be only triggered by Redis if there is not - * already a background process doing persistence. Specifically: If a Redis child is creating a - * snapshot on disk, the AOF rewrite is scheduled but not started until the saving child producing - * the RDB file terminates. In this case the BGREWRITEAOF will still return an OK code, but with - * an appropriate message. You can check if an AOF rewrite is scheduled looking at the INFO - * command as of Redis 2.6. If an AOF rewrite is already in progress the command returns an error - * and no AOF rewrite will be scheduled for a later time. Since Redis 2.4 the AOF rewrite is - * automatically triggered by Redis, however the BGREWRITEAOF command can be used to trigger a - * rewrite at any time. + * Instruct Redis to start an Append Only File rewrite process. The rewrite will create a small optimized version of the current Append Only File + * If BGREWRITEAOF fails, no data gets lost as the old AOF will be untouched. + The rewrite will be only triggered by Redis if there is not already a background process doing persistence. Specifically: + If a Redis child is creating a snapshot on disk, the AOF rewrite is scheduled but not started until the saving child producing the RDB file terminates. In this case the BGREWRITEAOF will still return an OK code, but with an appropriate message. You can check if an AOF rewrite is scheduled looking at the INFO command as of Redis 2.6. + If an AOF rewrite is already in progress the command returns an error and no AOF rewrite will be scheduled for a later time. + Since Redis 2.4 the AOF rewrite is automatically triggered by Redis, however the BGREWRITEAOF command can be used to trigger a rewrite at any time. * @return the response of the command */ String bgrewriteaof(); @@ -130,49 +91,37 @@ public interface BasicCommands { Long lastsave(); /** - * 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 + * 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 only in case of error. */ String shutdown(); /** - * The INFO command returns information and statistics about the server in a format that is simple - * to parse by computers and easy to read by humans. + * The INFO command returns information and statistics about the server in a format that is simple to parse by computers and easy to read by humans. * @return information on the server */ String info(); /** - * The INFO command returns information and statistics about the server in a format that is simple - * to parse by computers and easy to read by humans. - * @param section (all: Return all sections, default: Return only the default set of sections, - * server: General information about the Redis server, clients: Client connections - * section, memory: Memory consumption related information, persistence: RDB and AOF - * related information, stats: General statistics, replication: Master/slave replication - * information, cpu: CPU consumption statistics, commandstats: Redis command statistics, - * cluster: Redis Cluster section, keyspace: Database related statistics) + * The INFO command returns information and statistics about the server in a format that is simple to parse by computers and easy to read by humans. + * @param section (all: Return all sections, default: Return only the default set of sections, server: General information about the Redis server, clients: Client connections section, memory: Memory consumption related information, persistence: RDB and AOF related information, stats: General statistics, replication: Master/slave replication information, cpu: CPU consumption statistics, commandstats: Redis command statistics, cluster: Redis Cluster section, keyspace: Database related statistics) * @return */ String info(String section); /** - * The SLAVEOF command can change the replication settings of a slave on the fly. In the proper - * form SLAVEOF hostname port will make the server a slave of another 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. - * @param host listening at the specified hostname - * @param port server listening at the specified port - * @return result of the command. + * The SLAVEOF command can change the replication settings of a slave on the fly. In the proper form SLAVEOF hostname port will make the server a slave of another 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. + * @param host, listening at the specified hostname + * @param port, server listening at the specified port + * @return result of the commmand. */ String slaveof(String host, int port); /** - * SLAVEOF NO ONE will stop replication, turning the server into a MASTER, but will not discard - * the replication. So, if the old master stops working, it is possible to turn the slave into a - * master and set the application to use this new master in read/write. Later when the other Redis - * server is fixed, it can be reconfigured to work as a slave. + * SLAVEOF NO ONE will stop replication, turning the server into a MASTER, but will not discard the replication. So, if the old master stops working, it is possible to turn the slave into a master and set the application to use this new master in read/write. Later when the other Redis server is fixed, it can be reconfigured to work as a slave. * @return result of the command */ String slaveofNoOne(); @@ -189,15 +138,5 @@ public interface BasicCommands { String configRewrite(); - /** - * Blocks until all the previous write commands are successfully transferred and acknowledged by - * at least the specified number of replicas. If the timeout, specified in milliseconds, is - * reached, the command returns even if the specified number of replicas were not yet reached. - * @param replicas successfully transferred and acknowledged by at least the specified number of - * replicas - * @param timeout the time to block in milliseconds, a timeout of 0 means to block forever - * @return the number of replicas reached by all the writes performed in the context of the - * current connection - */ Long waitReplicas(int replicas, long timeout); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BasicRedisPipeline.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BasicRedisPipeline.java index 21bcc5322..c20ee0811 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BasicRedisPipeline.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BasicRedisPipeline.java @@ -2,7 +2,6 @@ package com.fr.third.redis.clients.jedis.commands; import com.fr.third.redis.clients.jedis.Module; import com.fr.third.redis.clients.jedis.Response; -import com.fr.third.redis.clients.jedis.args.FlushMode; import java.util.List; @@ -27,12 +26,8 @@ public interface BasicRedisPipeline { Response flushDB(); - Response flushDB(FlushMode flushMode); - Response flushAll(); - Response flushAll(FlushMode flushMode); - Response info(); Response> time(); @@ -47,8 +42,6 @@ public interface BasicRedisPipeline { Response swapDB(int index1, int index2); - Response migrate(String host, int port, String key, int destinationDB, int timeout); - Response moduleLoad(String path); Response> moduleList(); diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryJedisClusterCommands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryJedisClusterCommands.java index c72063fb5..9deb8a4b3 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryJedisClusterCommands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryJedisClusterCommands.java @@ -1,8 +1,12 @@ package com.fr.third.redis.clients.jedis.commands; import com.fr.third.redis.clients.jedis.*; -import com.fr.third.redis.clients.jedis.params.*; +import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; +import com.fr.third.redis.clients.jedis.params.SetParams; +import com.fr.third.redis.clients.jedis.params.ZAddParams; +import com.fr.third.redis.clients.jedis.params.ZIncrByParams; +import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; @@ -14,10 +18,6 @@ public interface BinaryJedisClusterCommands { byte[] get(byte[] key); - byte[] getDel(byte[] key); - - byte[] getEx(byte[] key, GetExParams params); - Boolean exists(byte[] key); Long persist(byte[] key); @@ -26,17 +26,7 @@ public interface BinaryJedisClusterCommands { 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); - - String restore(byte[] key, long ttl, byte[] serializedValue, RestoreParams params); + String restore(byte[] key, int ttl, byte[] serializedValue); Long expire(byte[] key, int seconds); @@ -66,15 +56,7 @@ public interface BinaryJedisClusterCommands { 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 setex(byte[] key, int seconds, byte[] value); String psetex(byte[] key, long milliseconds, byte[] value); @@ -116,16 +98,10 @@ public interface BinaryJedisClusterCommands { Set hkeys(byte[] key); - List hvals(byte[] key); + Collection 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); @@ -144,18 +120,8 @@ public interface BinaryJedisClusterCommands { 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); @@ -170,8 +136,6 @@ public interface BinaryJedisClusterCommands { Boolean sismember(byte[] key, byte[] member); - List smismember(byte[] key, byte[]... members); - byte[] srandmember(byte[] key); List srandmember(byte[] key, int count); @@ -186,8 +150,6 @@ public interface BinaryJedisClusterCommands { 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); @@ -206,26 +168,10 @@ public interface BinaryJedisClusterCommands { 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); @@ -276,11 +222,13 @@ public interface BinaryJedisClusterCommands { Set zrangeByLex(byte[] key, byte[] min, byte[] max); - Set zrangeByLex(byte[] key, byte[] min, byte[] max, int offset, int count); + 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); + Set zrevrangeByLex(byte[] key, byte[] max, byte[] min, int offset, + int count); Long zremrangeByLex(byte[] key, byte[] min, byte[] max); @@ -310,8 +258,6 @@ public interface BinaryJedisClusterCommands { 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); @@ -320,26 +266,16 @@ public interface BinaryJedisClusterCommands { 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); + GeoUnit unit); - List georadiusReadonly(byte[] key, double longitude, double latitude, - double radius, GeoUnit unit, GeoRadiusParam param); + List georadius(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); + GeoRadiusParam param); ScanResult> hscan(byte[] key, byte[] cursor); @@ -357,73 +293,14 @@ public interface BinaryJedisClusterCommands { * Executes BITFIELD Redis command * @param key * @param arguments - * @return */ List bitfield(byte[] key, byte[]... arguments); - - List bitfieldReadonly(byte[] key, byte[]... arguments); - + /** * Used for HSTRLEN Redis command - * @param key + * @param key * @param field - * @return */ 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 - List xrange(byte[] key, byte[] start, byte[] end, long count); - - 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(final byte[] key, final 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); - - Long waitReplicas(byte[] key, int replicas, long timeout); - - Long memoryUsage(byte[] key); - - Long memoryUsage(byte[] key, int samples); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryJedisCommands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryJedisCommands.java index 708b2c473..a3c826bff 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryJedisCommands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryJedisCommands.java @@ -1,11 +1,15 @@ package com.fr.third.redis.clients.jedis.commands; +import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import com.fr.third.redis.clients.jedis.*; -import com.fr.third.redis.clients.jedis.params.*; +import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; +import com.fr.third.redis.clients.jedis.params.SetParams; +import com.fr.third.redis.clients.jedis.params.ZAddParams; +import com.fr.third.redis.clients.jedis.params.ZIncrByParams; /** * Common interface for sharded and non-sharded BinaryJedis @@ -17,10 +21,6 @@ public interface BinaryJedisCommands { byte[] get(byte[] key); - byte[] getDel(byte[] key); - - byte[] getEx(byte[] key, GetExParams params); - Boolean exists(byte[] key); Long persist(byte[] key); @@ -29,41 +29,9 @@ public interface BinaryJedisCommands { 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 #restoreReplace(byte[], long, byte[])}. - */ - @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); - } + String restore(byte[] key, int ttl, byte[] serializedValue); - Long expire(byte[] key, long seconds); + Long expire(byte[] key, int seconds); Long pexpire(byte[] key, long milliseconds); @@ -91,15 +59,7 @@ public interface BinaryJedisCommands { 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 setex(byte[] key, int seconds, byte[] value); String psetex(byte[] key, long milliseconds, byte[] value); @@ -141,16 +101,10 @@ public interface BinaryJedisCommands { Set hkeys(byte[] key); - List hvals(byte[] key); + Collection 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); @@ -169,18 +123,8 @@ public interface BinaryJedisCommands { 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); @@ -195,8 +139,6 @@ public interface BinaryJedisCommands { Boolean sismember(byte[] key, byte[] member); - List smismember(byte[] key, byte[]... members); - byte[] srandmember(byte[] key); List srandmember(byte[] key, int count); @@ -211,8 +153,6 @@ public interface BinaryJedisCommands { 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); @@ -231,26 +171,10 @@ public interface BinaryJedisCommands { 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); @@ -301,11 +225,13 @@ public interface BinaryJedisCommands { Set zrangeByLex(byte[] key, byte[] min, byte[] max); - Set zrangeByLex(byte[] key, byte[] min, byte[] max, int offset, int count); + 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); + Set zrevrangeByLex(byte[] key, byte[] max, byte[] min, int offset, + int count); Long zremrangeByLex(byte[] key, byte[] min, byte[] max); @@ -337,8 +263,6 @@ public interface BinaryJedisCommands { 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); @@ -348,26 +272,15 @@ public interface BinaryJedisCommands { 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); + 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); + 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); + GeoRadiusParam param); ScanResult> hscan(byte[] key, byte[] cursor); @@ -385,92 +298,15 @@ public interface BinaryJedisCommands { * Executes BITFIELD Redis command * @param key * @param arguments - * @return */ List bitfield(byte[] key, byte[]... arguments); - - List bitfieldReadonly(byte[] key, byte[]... arguments); - + /** * Used for HSTRLEN Redis command - * @param key + * @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); - - /** - * @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); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryRedisPipeline.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryRedisPipeline.java index f38e5c544..cbfa9314a 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryRedisPipeline.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryRedisPipeline.java @@ -1,7 +1,10 @@ package com.fr.third.redis.clients.jedis.commands; import com.fr.third.redis.clients.jedis.*; -import com.fr.third.redis.clients.jedis.params.*; + +import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; +import com.fr.third.redis.clients.jedis.params.ZAddParams; +import com.fr.third.redis.clients.jedis.params.ZIncrByParams; import java.util.List; import java.util.Map; @@ -26,15 +29,7 @@ public interface BinaryRedisPipeline { 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 expire(byte[] key, int seconds); Response pexpire(byte[] key, long milliseconds); @@ -44,10 +39,6 @@ public interface BinaryRedisPipeline { 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); @@ -80,12 +71,6 @@ public interface BinaryRedisPipeline { 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); @@ -98,14 +83,6 @@ public interface BinaryRedisPipeline { 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); @@ -124,8 +101,6 @@ public interface BinaryRedisPipeline { Response rpop(byte[] key); - Response> rpop(byte[] key, int count); - Response rpush(byte[] key, byte[]... string); Response rpushx(byte[] key, byte[]... string); @@ -140,15 +115,7 @@ public interface BinaryRedisPipeline { 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 setex(byte[] key, int seconds, byte[] value); Response setnx(byte[] key, byte[] value); @@ -158,8 +125,6 @@ public interface BinaryRedisPipeline { Response sismember(byte[] key, byte[] member); - Response> smismember(byte[] key, byte[]... members); - Response> sort(byte[] key); Response> sort(byte[] key, SortingParams sortingParameters); @@ -192,8 +157,6 @@ public interface BinaryRedisPipeline { 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); @@ -218,9 +181,11 @@ public interface BinaryRedisPipeline { Response> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max); - Response> zrangeByScoreWithScores(byte[] key, double min, double max, int offset, int count); + 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> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, int offset, + int count); Response> zrevrangeByScore(byte[] key, double max, double min); @@ -234,9 +199,11 @@ public interface BinaryRedisPipeline { Response> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min); - Response> zrevrangeByScoreWithScores(byte[] key, double max, double min, 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> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, int offset, + int count); Response> zrangeWithScores(byte[] key, long start, long stop); @@ -254,35 +221,21 @@ public interface BinaryRedisPipeline { 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> 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> zrevrangeByLex(byte[] key, byte[] max, byte[] min, + int offset, int count); Response zremrangeByLex(byte[] key, byte[] min, byte[] max); @@ -294,44 +247,12 @@ public interface BinaryRedisPipeline { 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 #restoreReplace(byte[], long, byte[])}. - */ - @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); @@ -341,107 +262,18 @@ public interface BinaryRedisPipeline { 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); + 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); + 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); + 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); + 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 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); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryScriptingCommands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryScriptingCommands.java index 9e17e6860..f93edf0ec 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryScriptingCommands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/BinaryScriptingCommands.java @@ -1,7 +1,5 @@ package com.fr.third.redis.clients.jedis.commands; -import com.fr.third.redis.clients.jedis.args.FlushMode; - import java.util.List; public interface BinaryScriptingCommands { @@ -27,7 +25,5 @@ public interface BinaryScriptingCommands { String scriptFlush(); - String scriptFlush(FlushMode flushMode); - String scriptKill(); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/Commands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/Commands.java index cbb018d33..d06f5d497 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/Commands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/Commands.java @@ -1,49 +1,24 @@ package com.fr.third.redis.clients.jedis.commands; import java.util.Map; -import java.util.Map.Entry; import com.fr.third.redis.clients.jedis.BitOP; -import com.fr.third.redis.clients.jedis.StreamEntryID; import com.fr.third.redis.clients.jedis.ListPosition; import com.fr.third.redis.clients.jedis.ScanParams; import com.fr.third.redis.clients.jedis.SortingParams; -import com.fr.third.redis.clients.jedis.args.ListDirection; -import com.fr.third.redis.clients.jedis.args.UnblockType; import com.fr.third.redis.clients.jedis.ZParams; -import com.fr.third.redis.clients.jedis.params.GetExParams; -import com.fr.third.redis.clients.jedis.params.MigrateParams; -import com.fr.third.redis.clients.jedis.params.ClientKillParams; -import com.fr.third.redis.clients.jedis.params.RestoreParams; import com.fr.third.redis.clients.jedis.params.SetParams; -import com.fr.third.redis.clients.jedis.params.XAddParams; -import com.fr.third.redis.clients.jedis.params.XClaimParams; -import com.fr.third.redis.clients.jedis.params.XPendingParams; -import com.fr.third.redis.clients.jedis.params.XTrimParams; import com.fr.third.redis.clients.jedis.params.ZAddParams; import com.fr.third.redis.clients.jedis.params.ZIncrByParams; -import com.fr.third.redis.clients.jedis.params.LPosParams; -import com.fr.third.redis.clients.jedis.params.XReadGroupParams; -import com.fr.third.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); @@ -58,15 +33,7 @@ public interface Commands { 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 expire(String key, int seconds); void expireAt(String key, long unixTime); @@ -94,15 +61,7 @@ public interface Commands { 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 setex(String key, int seconds, String value); void mset(String... keysvalues); @@ -148,12 +107,6 @@ public interface Commands { 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); @@ -174,18 +127,8 @@ public interface Commands { 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); @@ -204,8 +147,6 @@ public interface Commands { void sismember(String key, String member); - void smismember(String key, String... members); - void sinter(String... keys); void sinterstore(String dstkey, String... keys); @@ -218,10 +159,6 @@ public interface Commands { 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); @@ -232,10 +169,6 @@ public interface Commands { 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); @@ -254,58 +187,26 @@ public interface Commands { 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 sort(String key, SortingParams sortingParameters, String dstkey); - void blpop(double timeout, String... keys); + void sort(String key, String dstkey); 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); @@ -314,33 +215,39 @@ public interface Commands { void zrangeByScore(String key, String min, String max); - void zrangeByScore(String key, double min, double max, int offset, int count); + 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, 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 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, 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, 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 zrevrangeByScoreWithScores(String key, String max, String min, + int offset, int count); void zremrangeByRank(String key, long start, long stop); @@ -348,18 +255,10 @@ public interface Commands { 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); @@ -402,44 +301,12 @@ public interface Commands { 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 #restoreReplace(java.lang.String, long, byte[])}. - */ - @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 hscan(String key, String cursor, ScanParams params); @@ -457,113 +324,10 @@ public interface Commands { */ 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 clientKill(String ipPort); - - void clientKill(String ip, int port); - - void clientKill(ClientKillParams params); - - void clientGetname(); - - void clientList(); - - 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 xinfoStream (String key); - - void xinfoGroup (String key); - - void xinfoConsumers (String key, String group); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisClusterBinaryScriptingCommands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisClusterBinaryScriptingCommands.java index f3617d299..b5f790f4c 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisClusterBinaryScriptingCommands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisClusterBinaryScriptingCommands.java @@ -1,7 +1,5 @@ package com.fr.third.redis.clients.jedis.commands; -import com.fr.third.redis.clients.jedis.args.FlushMode; - import java.util.List; public interface JedisClusterBinaryScriptingCommands { @@ -13,17 +11,15 @@ public interface JedisClusterBinaryScriptingCommands { /** * @param script - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - * @return + * @param sampleKey Command will be executed in the node where the hash slot of this key is assigned to + * @return */ 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 - * @return + * @param sampleKey Command will be executed in the node where the hash slot of this key is assigned to + * @return */ Object evalsha(byte[] sha1, byte[] sampleKey); @@ -32,40 +28,28 @@ public interface JedisClusterBinaryScriptingCommands { 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 sampleKey Command will be executed in the node where the hash slot of this key is assigned to * @param sha1 - * @return + * @return */ 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 - * @return + * @param sampleKey Command will be executed in the node where the hash slot of this key is assigned to + * @return */ 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 - * @return + * @param sampleKey Command will be executed in the node where the hash slot of this key is assigned to + * @return */ 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 - * @return - */ - 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 - * @return + * @param sampleKey Command will be executed in the node where the hash slot of this key is assigned to + * @return */ String scriptKill(byte[] sampleKey); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisClusterCommands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisClusterCommands.java index f5c39306e..e7e2fc590 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisClusterCommands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisClusterCommands.java @@ -1,29 +1,10 @@ package com.fr.third.redis.clients.jedis.commands; -import com.fr.third.redis.clients.jedis.StreamEntryID; -import com.fr.third.redis.clients.jedis.GeoCoordinate; -import com.fr.third.redis.clients.jedis.GeoRadiusResponse; -import com.fr.third.redis.clients.jedis.GeoUnit; -import com.fr.third.redis.clients.jedis.ListPosition; -import com.fr.third.redis.clients.jedis.StreamPendingEntry; -import com.fr.third.redis.clients.jedis.ScanResult; -import com.fr.third.redis.clients.jedis.SortingParams; -import com.fr.third.redis.clients.jedis.StreamEntry; -import com.fr.third.redis.clients.jedis.StreamPendingSummary; -import com.fr.third.redis.clients.jedis.Tuple; -import com.fr.third.redis.clients.jedis.params.GeoAddParams; +import com.fr.third.redis.clients.jedis.*; import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; -import com.fr.third.redis.clients.jedis.params.GetExParams; -import com.fr.third.redis.clients.jedis.params.RestoreParams; import com.fr.third.redis.clients.jedis.params.SetParams; -import com.fr.third.redis.clients.jedis.params.XAddParams; -import com.fr.third.redis.clients.jedis.params.XClaimParams; -import com.fr.third.redis.clients.jedis.params.XPendingParams; -import com.fr.third.redis.clients.jedis.params.XTrimParams; import com.fr.third.redis.clients.jedis.params.ZAddParams; import com.fr.third.redis.clients.jedis.params.ZIncrByParams; -import com.fr.third.redis.clients.jedis.params.LPosParams; -import com.fr.third.redis.clients.jedis.resps.KeyedListElement; import java.util.List; import java.util.Map; @@ -36,10 +17,6 @@ public interface JedisClusterCommands { String get(String key); - String getDel(String key); - - String getEx(String key, GetExParams params); - Boolean exists(String key); Long persist(String key); @@ -48,27 +25,9 @@ public interface JedisClusterCommands { 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); - - 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); - } + String restore(String key, int ttl, byte[] serializedValue); - Long expire(String key, long seconds); + Long expire(String key, int seconds); Long pexpire(String key, long milliseconds); @@ -96,15 +55,7 @@ public interface JedisClusterCommands { 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 setex(String key, int seconds, String value); String psetex(String key, long milliseconds, String value); @@ -136,8 +87,6 @@ public interface JedisClusterCommands { 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); @@ -150,12 +99,6 @@ public interface JedisClusterCommands { 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); @@ -174,18 +117,8 @@ public interface JedisClusterCommands { 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); @@ -200,8 +133,6 @@ public interface JedisClusterCommands { Boolean sismember(String key, String member); - List smismember(String key, String... members); - String srandmember(String key); List srandmember(String key, int count); @@ -216,8 +147,6 @@ public interface JedisClusterCommands { 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); @@ -236,26 +165,10 @@ public interface JedisClusterCommands { 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); @@ -306,11 +219,13 @@ public interface JedisClusterCommands { Set zrangeByLex(String key, String min, String max); - Set zrangeByLex(String key, String min, String max, int offset, int count); + 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); + Set zrevrangeByLex(String key, String max, String min, + int offset, int count); Long zremrangeByLex(String key, String min, String max); @@ -322,12 +237,8 @@ public interface JedisClusterCommands { 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); @@ -354,8 +265,6 @@ public interface JedisClusterCommands { 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); @@ -365,274 +274,28 @@ public interface JedisClusterCommands { 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); + 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); + 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); + GeoRadiusParam param); /** * Executes BITFIELD Redis command * @param key * @param arguments - * @return */ - List bitfield(String key, String...arguments); - - List bitfieldReadonly(String key, String...arguments); - + List bitfield(String key, String... arguments); + /** * Used for HSTRLEN Redis command - * @param key + * @param key * @param field * @return lenth of the value for key */ Long hstrlen(String key, String field); - - /** - * MEMORY USAGE key - * - * @param key - * @return the memory usage - */ - Long memoryUsage(String key); - - /** - * MEMORY USAGE key [SAMPLES count] - * - * @param key - * @param samples - * @return the memory usage - */ - Long memoryUsage(String key, int samples); - - - /** - * 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 - * @return - */ - 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 - * @return - */ - StreamEntryID xadd(String key, Map hash, XAddParams params); - - /** - * XLEN key - * - * @param key - * @return - */ - Long xlen(String key); - - /** - * XRANGE key start end - * - * @param key - * @param start - * @param end - * @return - */ - List xrange(String key, StreamEntryID start, StreamEntryID end); - - /** - * XRANGE key start end COUNT count - * - * @param key - * @param start - * @param end - * @param count - * @return - */ - List xrange(String key, StreamEntryID start, StreamEntryID end, int count); - - /** - * XREVRANGE key end start - * @param key - * @param end - * @param start - * @return - */ - List xrevrange(String key, StreamEntryID end, StreamEntryID start); - - /** - * XREVRANGE key end start COUNT count - * @param key - * @param end - * @param start - * @param count - * @return - */ - List xrevrange(String key, StreamEntryID end, StreamEntryID start, int count); - - /** - * @deprecated This will be removed in future version. Use - * {@link MultiKeyJedisClusterCommands#xread(int, long, java.util.Map.Entry...)}. - */ - @Deprecated - List>> xread(int count, long block, Map.Entry... streams); - - /** - * XACK key group ID [ID ...] - * @param key - * @param group - * @param ids - * @return - */ - Long xack(String key, String group, StreamEntryID... ids); - - /** - * XGROUP CREATE - * - * @param key - * @param groupname - * @param id - * @return - */ - String xgroupCreate( String key, String groupname, StreamEntryID id, boolean makeStream); - - /** - * XGROUP SETID - * - * @param key - * @param groupname - * @param id - * @return - */ - String xgroupSetID( String key, String groupname, StreamEntryID id); - - /** - * XGROUP DESTROY - * - * @param key - * @param groupname - * @return - */ - Long xgroupDestroy( String key, String groupname); - - /** - * XGROUP DELCONSUMER - * @param key - * @param groupname - * @param consumername - * @return - */ - Long xgroupDelConsumer( String key, String groupname, String consumername); - - /** - * @deprecated This will be removed in future version. Use - * {@link MultiKeyJedisClusterCommands#xreadGroup(java.lang.String, java.lang.String, int, long, boolean, java.util.Map.Entry...)}. - */ - @Deprecated - List>> xreadGroup(String groupname, String consumer, int count, long block, boolean noAck, Map.Entry... streams); - - /** - * XPENDING key group - * - * @param key - * @param groupname - * @return - */ - 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 - * @return - */ - 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 - * @return - */ - List xpending(String key, String groupname, XPendingParams params); - - /** - * XDEL key ID [ID ...] - * @param key - * @param ids - * @return - */ - Long xdel( String key, StreamEntryID... ids); - - /** - * XTRIM key MAXLEN [~] count - * @param key - * @param maxLen - * @param approximateLength - * @return - */ - Long xtrim( String key, long maxLen, boolean approximateLength); - - /** - * XTRIM key MAXLEN|MINID [=|~] threshold [LIMIT count] - * @param key - * @param params - * @return - */ - 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); - - List xclaim(String key, String group, String consumername, long minIdleTime, - XClaimParams params, StreamEntryID... ids); - - List xclaimJustId(String key, String group, String consumername, long minIdleTime, - XClaimParams params, StreamEntryID... ids); - - Long waitReplicas(String key, int replicas, long timeout); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisClusterScriptingCommands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisClusterScriptingCommands.java index 3aaca53f5..b4c52b576 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisClusterScriptingCommands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisClusterScriptingCommands.java @@ -9,17 +9,15 @@ public interface JedisClusterScriptingCommands { /** * @param script - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - * @return + * @param sampleKey Command will be executed in the node where the hash slot of this key is assigned to + * @return */ 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 - * @return + * @param sampleKey Command will be executed in the node where the hash slot of this key is assigned to + * @return */ Object evalsha(String sha1, String sampleKey); @@ -29,39 +27,34 @@ public interface JedisClusterScriptingCommands { /** * @param sha1 - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - * @return + * @param sampleKey Command will be executed in the node where the hash slot of this key is assigned to + * @return */ 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 sampleKey Command will be executed in the node where the hash slot of this key is assigned to * @param sha1 - * @return + * @return */ 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 - * @return + * @param sampleKey Command will be executed in the node where the hash slot of this key is assigned to + * @return */ 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 - * @return + * @param sampleKey Command will be executed in the node where the hash slot of this key is assigned to + * @return */ String scriptFlush(String sampleKey); /** - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - * @return + * @param sampleKey Command will be executed in the node where the hash slot of this key is assigned to + * @return */ String scriptKill(String sampleKey); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisCommands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisCommands.java index a42e7fd91..0a2a1f6e6 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisCommands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/JedisCommands.java @@ -4,35 +4,11 @@ import java.util.List; import java.util.Map; import java.util.Set; -import com.fr.third.redis.clients.jedis.BitPosParams; -import com.fr.third.redis.clients.jedis.StreamConsumersInfo; -import com.fr.third.redis.clients.jedis.StreamEntryID; -import com.fr.third.redis.clients.jedis.GeoCoordinate; -import com.fr.third.redis.clients.jedis.GeoRadiusResponse; -import com.fr.third.redis.clients.jedis.GeoUnit; -import com.fr.third.redis.clients.jedis.ListPosition; -import com.fr.third.redis.clients.jedis.StreamGroupInfo; -import com.fr.third.redis.clients.jedis.StreamInfo; -import com.fr.third.redis.clients.jedis.StreamPendingEntry; -import com.fr.third.redis.clients.jedis.ScanParams; -import com.fr.third.redis.clients.jedis.ScanResult; -import com.fr.third.redis.clients.jedis.SortingParams; -import com.fr.third.redis.clients.jedis.StreamEntry; -import com.fr.third.redis.clients.jedis.StreamPendingSummary; -import com.fr.third.redis.clients.jedis.Tuple; -import com.fr.third.redis.clients.jedis.params.GeoAddParams; +import com.fr.third.redis.clients.jedis.*; import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; -import com.fr.third.redis.clients.jedis.params.GetExParams; -import com.fr.third.redis.clients.jedis.params.RestoreParams; import com.fr.third.redis.clients.jedis.params.SetParams; -import com.fr.third.redis.clients.jedis.params.XAddParams; -import com.fr.third.redis.clients.jedis.params.XClaimParams; -import com.fr.third.redis.clients.jedis.params.XPendingParams; -import com.fr.third.redis.clients.jedis.params.XTrimParams; import com.fr.third.redis.clients.jedis.params.ZAddParams; import com.fr.third.redis.clients.jedis.params.ZIncrByParams; -import com.fr.third.redis.clients.jedis.params.LPosParams; -import com.fr.third.redis.clients.jedis.resps.KeyedListElement; /** * Common interface for sharded and non-sharded Jedis @@ -44,10 +20,6 @@ public interface JedisCommands { String get(String key); - String getDel(String key); - - String getEx(String key, GetExParams params); - Boolean exists(String key); Long persist(String key); @@ -56,41 +28,9 @@ public interface JedisCommands { 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 #restoreReplace(java.lang.String, long, byte[])}. - */ - @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); + String restore(String key, int ttl, byte[] serializedValue); - /** - * @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 expire(String key, int seconds); Long pexpire(String key, long milliseconds); @@ -118,15 +58,7 @@ public interface JedisCommands { 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 setex(String key, int seconds, String value); String psetex(String key, long milliseconds, String value); @@ -172,12 +104,6 @@ public interface JedisCommands { 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); @@ -196,18 +122,8 @@ public interface JedisCommands { 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); @@ -222,8 +138,6 @@ public interface JedisCommands { Boolean sismember(String key, String member); - List smismember(String key, String... members); - String srandmember(String key); List srandmember(String key, int count); @@ -238,8 +152,6 @@ public interface JedisCommands { 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); @@ -258,26 +170,10 @@ public interface JedisCommands { 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); @@ -328,11 +224,13 @@ public interface JedisCommands { Set zrangeByLex(String key, String min, String max); - Set zrangeByLex(String key, String min, String max, int offset, int count); + 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); + Set zrevrangeByLex(String key, String max, String min, + int offset, int count); Long zremrangeByLex(String key, String min, String max); @@ -344,12 +242,8 @@ public interface JedisCommands { 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); @@ -368,7 +262,8 @@ public interface JedisCommands { ScanResult> hscan(String key, String cursor); - ScanResult> hscan(String key, String cursor, ScanParams params); + ScanResult> hscan(String key, String cursor, + ScanParams params); ScanResult sscan(String key, String cursor); @@ -388,8 +283,6 @@ public interface JedisCommands { 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); @@ -399,277 +292,28 @@ public interface JedisCommands { 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); + 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); + 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); + GeoRadiusParam param); /** * Executes BITFIELD Redis command * @param key * @param arguments - * @return */ - List bitfield(String key, String...arguments); - - List bitfieldReadonly(String key, String...arguments); - + List bitfield(String key, String... arguments); + /** * Used for HSTRLEN Redis command - * @param key + * @param key * @param field - * @return length of the value for key + * @return lenth 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 - * @return - */ - 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 - * @return - */ - StreamEntryID xadd(String key, Map hash, XAddParams params); - - /** - * XLEN key - * - * @param key - * @return - */ - 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 - * @return - */ - long xack(String key, String group, StreamEntryID... ids); - - /** - * XGROUP CREATE - * - * @param key - * @param groupname - * @param id - * @param makeStream - * @return - */ - String xgroupCreate( String key, String groupname, StreamEntryID id, boolean makeStream); - - /** - * XGROUP SETID - * - * @param key - * @param groupname - * @param id - * @return - */ - String xgroupSetID( String key, String groupname, StreamEntryID id); - - /** - * XGROUP DESTROY - * - * @param key - * @param groupname - * @return - */ - long xgroupDestroy( String key, String groupname); - - /** - * XGROUP DELCONSUMER - * @param key - * @param groupname - * @param consumername - * @return - */ - Long xgroupDelConsumer( String key, String groupname, String consumername); - - /** - * XPENDING key group - * - * @param key - * @param groupname - * @return - */ - 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 - * @return - */ - 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 - * @return - */ - long xdel( String key, StreamEntryID... ids); - - /** - * XTRIM key MAXLEN [~] count - * @param key - * @param maxLen - * @param approximate - * @return - */ - long xtrim( String key, long maxLen, boolean approximate); - - /** - * XTRIM key MAXLEN|MINID [=|~] threshold [LIMIT count] - * @param key - * @param params - * @return - */ - 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); - - /** - * 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); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/ModuleCommands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/ModuleCommands.java index 5e6ef4844..0df17f45a 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/ModuleCommands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/ModuleCommands.java @@ -5,10 +5,7 @@ import com.fr.third.redis.clients.jedis.Module; import java.util.List; public interface ModuleCommands { - String moduleLoad(String path); - String moduleUnload(String name); - List moduleList(); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyBinaryCommands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyBinaryCommands.java index 65250c277..5aec57078 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyBinaryCommands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyBinaryCommands.java @@ -2,52 +2,27 @@ package com.fr.third.redis.clients.jedis.commands; import com.fr.third.redis.clients.jedis.BinaryJedisPubSub; import com.fr.third.redis.clients.jedis.BitOP; -import com.fr.third.redis.clients.jedis.GeoUnit; import com.fr.third.redis.clients.jedis.SortingParams; -import com.fr.third.redis.clients.jedis.Tuple; import com.fr.third.redis.clients.jedis.ZParams; -import com.fr.third.redis.clients.jedis.args.*; -import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; -import com.fr.third.redis.clients.jedis.params.GeoRadiusStoreParam; -import com.fr.third.redis.clients.jedis.params.XReadGroupParams; -import com.fr.third.redis.clients.jedis.params.XReadParams; 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); @@ -84,24 +59,10 @@ public interface MultiKeyBinaryCommands { 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); @@ -123,30 +84,4 @@ public interface MultiKeyBinaryCommands { Long pfcount(byte[]... keys); Long touch(byte[]... keys); - - /** - * @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 #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); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyBinaryJedisClusterCommands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyBinaryJedisClusterCommands.java index 1ccdd0346..c9281f332 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyBinaryJedisClusterCommands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyBinaryJedisClusterCommands.java @@ -2,48 +2,25 @@ package com.fr.third.redis.clients.jedis.commands; import com.fr.third.redis.clients.jedis.BinaryJedisPubSub; import com.fr.third.redis.clients.jedis.BitOP; -import com.fr.third.redis.clients.jedis.GeoUnit; import com.fr.third.redis.clients.jedis.ScanParams; import com.fr.third.redis.clients.jedis.ScanResult; import com.fr.third.redis.clients.jedis.SortingParams; -import com.fr.third.redis.clients.jedis.Tuple; import com.fr.third.redis.clients.jedis.ZParams; -import com.fr.third.redis.clients.jedis.args.*; -import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; -import com.fr.third.redis.clients.jedis.params.GeoRadiusStoreParam; -import com.fr.third.redis.clients.jedis.params.XReadGroupParams; -import com.fr.third.redis.clients.jedis.params.XReadParams; import java.util.List; -import java.util.Map; -import java.util.Map.Entry; import java.util.Set; public interface MultiKeyBinaryJedisClusterCommands { - 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 bzpopmax(double timeout, byte[]... keys); - - List bzpopmin(double timeout, byte[]... keys); - List mget(byte[]... keys); String mset(byte[]... keysvalues); @@ -74,24 +51,10 @@ public interface MultiKeyBinaryJedisClusterCommands { Long sunionstore(byte[] dstkey, 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); @@ -115,30 +78,4 @@ public interface MultiKeyBinaryJedisClusterCommands { ScanResult scan(byte[] cursor, ScanParams params); Set keys(byte[] pattern); - - /** - * @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 #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); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyBinaryRedisPipeline.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyBinaryRedisPipeline.java index 91661a82c..60224e1d9 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyBinaryRedisPipeline.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyBinaryRedisPipeline.java @@ -1,25 +1,17 @@ package com.fr.third.redis.clients.jedis.commands; import com.fr.third.redis.clients.jedis.BitOP; -import com.fr.third.redis.clients.jedis.GeoUnit; import com.fr.third.redis.clients.jedis.Response; import com.fr.third.redis.clients.jedis.SortingParams; -import com.fr.third.redis.clients.jedis.Tuple; import com.fr.third.redis.clients.jedis.ZParams; -import com.fr.third.redis.clients.jedis.args.*; -import com.fr.third.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); @@ -27,22 +19,10 @@ public interface MultiKeyBinaryRedisPipeline { 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); @@ -77,26 +57,10 @@ public interface MultiKeyBinaryRedisPipeline { Response watch(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); @@ -114,31 +78,4 @@ public interface MultiKeyBinaryRedisPipeline { 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 #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); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyCommands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyCommands.java index 723d55613..f275493fc 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyCommands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyCommands.java @@ -1,72 +1,37 @@ package com.fr.third.redis.clients.jedis.commands; -import com.fr.third.redis.clients.jedis.BitOP; -import com.fr.third.redis.clients.jedis.GeoUnit; -import com.fr.third.redis.clients.jedis.resps.KeyedZSetElement; -import com.fr.third.redis.clients.jedis.StreamEntryID; -import com.fr.third.redis.clients.jedis.JedisPubSub; -import com.fr.third.redis.clients.jedis.ScanParams; -import com.fr.third.redis.clients.jedis.ScanResult; -import com.fr.third.redis.clients.jedis.SortingParams; -import com.fr.third.redis.clients.jedis.StreamEntry; -import com.fr.third.redis.clients.jedis.Tuple; -import com.fr.third.redis.clients.jedis.ZParams; -import com.fr.third.redis.clients.jedis.args.*; -import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; -import com.fr.third.redis.clients.jedis.params.GeoRadiusStoreParam; -import com.fr.third.redis.clients.jedis.params.XReadGroupParams; -import com.fr.third.redis.clients.jedis.params.XReadParams; -import com.fr.third.redis.clients.jedis.resps.*; +import com.fr.third.redis.clients.jedis.*; 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. + * 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. + * 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: *

        @@ -119,24 +84,10 @@ public interface MultiKeyCommands { 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); @@ -155,51 +106,45 @@ public interface MultiKeyCommands { /** * @see #scan(String, ScanParams) - * - * @param cursor - * @return */ 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. + * 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 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. + * 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. + *
        • 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: + * 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. + *
        • 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. + * 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 @@ -212,47 +157,4 @@ public interface MultiKeyCommands { 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 #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); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyCommandsPipeline.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyCommandsPipeline.java index 22f62d83c..4a2417fed 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyCommandsPipeline.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyCommandsPipeline.java @@ -1,56 +1,27 @@ package com.fr.third.redis.clients.jedis.commands; import com.fr.third.redis.clients.jedis.BitOP; -import com.fr.third.redis.clients.jedis.GeoUnit; import com.fr.third.redis.clients.jedis.Response; import com.fr.third.redis.clients.jedis.SortingParams; -import com.fr.third.redis.clients.jedis.StreamEntry; -import com.fr.third.redis.clients.jedis.StreamEntryID; -import com.fr.third.redis.clients.jedis.Tuple; import com.fr.third.redis.clients.jedis.ZParams; -import com.fr.third.redis.clients.jedis.args.*; -import com.fr.third.redis.clients.jedis.params.*; -import com.fr.third.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); @@ -85,26 +56,10 @@ public interface MultiKeyCommandsPipeline { Response watch(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); @@ -122,33 +77,4 @@ public interface MultiKeyCommandsPipeline { 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); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyJedisClusterCommands.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyJedisClusterCommands.java index a85f38801..ee300097a 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyJedisClusterCommands.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/MultiKeyJedisClusterCommands.java @@ -1,51 +1,26 @@ package com.fr.third.redis.clients.jedis.commands; import com.fr.third.redis.clients.jedis.BitOP; -import com.fr.third.redis.clients.jedis.GeoUnit; import com.fr.third.redis.clients.jedis.JedisPubSub; import com.fr.third.redis.clients.jedis.ScanParams; import com.fr.third.redis.clients.jedis.ScanResult; import com.fr.third.redis.clients.jedis.SortingParams; -import com.fr.third.redis.clients.jedis.StreamEntry; -import com.fr.third.redis.clients.jedis.StreamEntryID; -import com.fr.third.redis.clients.jedis.Tuple; import com.fr.third.redis.clients.jedis.ZParams; -import com.fr.third.redis.clients.jedis.args.*; -import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; -import com.fr.third.redis.clients.jedis.params.GeoRadiusStoreParam; -import com.fr.third.redis.clients.jedis.params.XReadGroupParams; -import com.fr.third.redis.clients.jedis.params.XReadParams; -import com.fr.third.redis.clients.jedis.resps.*; import java.util.List; -import java.util.Map; import java.util.Set; public interface MultiKeyJedisClusterCommands { - 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); - - KeyedZSetElement bzpopmax(double timeout, String... keys); - - KeyedZSetElement bzpopmin(double timeout, String... keys); - List mget(String... keys); String mset(String... keysvalues); @@ -76,24 +51,10 @@ public interface MultiKeyJedisClusterCommands { Long sunionstore(String dstkey, String... keys); - Set zdiff(String... keys); - - Set zdiffWithScores(String... keys); - - Long zdiffStore(String dstkey, String... keys); - - Set zinter(ZParams params, String... keys); - - Set zinterWithScores(ZParams params, String... keys); - Long zinterstore(String dstkey, String... sets); Long zinterstore(String dstkey, ZParams params, String... sets); - 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); @@ -117,48 +78,4 @@ public interface MultiKeyJedisClusterCommands { ScanResult scan(String cursor, ScanParams params); Set keys(String pattern); - - 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); - - /** - * 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 #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); - } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/ProtocolCommand.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/ProtocolCommand.java index 4929995e1..22f52f755 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/ProtocolCommand.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/ProtocolCommand.java @@ -1,6 +1,7 @@ package com.fr.third.redis.clients.jedis.commands; -import com.fr.third.redis.clients.jedis.args.Rawable; +public interface ProtocolCommand { + + byte[] getRaw(); -public interface ProtocolCommand extends Rawable { } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/RedisPipeline.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/RedisPipeline.java index cd31d06dd..798e75a87 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/RedisPipeline.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/commands/RedisPipeline.java @@ -1,29 +1,9 @@ package com.fr.third.redis.clients.jedis.commands; -import com.fr.third.redis.clients.jedis.StreamEntryID; -import com.fr.third.redis.clients.jedis.BitPosParams; -import com.fr.third.redis.clients.jedis.GeoCoordinate; -import com.fr.third.redis.clients.jedis.GeoRadiusResponse; -import com.fr.third.redis.clients.jedis.GeoUnit; -import com.fr.third.redis.clients.jedis.ListPosition; -import com.fr.third.redis.clients.jedis.StreamPendingEntry; -import com.fr.third.redis.clients.jedis.Response; -import com.fr.third.redis.clients.jedis.SortingParams; -import com.fr.third.redis.clients.jedis.StreamEntry; -import com.fr.third.redis.clients.jedis.StreamPendingSummary; -import com.fr.third.redis.clients.jedis.Tuple; -import com.fr.third.redis.clients.jedis.params.GeoAddParams; +import com.fr.third.redis.clients.jedis.*; import com.fr.third.redis.clients.jedis.params.GeoRadiusParam; -import com.fr.third.redis.clients.jedis.params.GetExParams; -import com.fr.third.redis.clients.jedis.params.RestoreParams; -import com.fr.third.redis.clients.jedis.params.SetParams; -import com.fr.third.redis.clients.jedis.params.XAddParams; -import com.fr.third.redis.clients.jedis.params.XClaimParams; -import com.fr.third.redis.clients.jedis.params.XPendingParams; -import com.fr.third.redis.clients.jedis.params.XTrimParams; import com.fr.third.redis.clients.jedis.params.ZAddParams; import com.fr.third.redis.clients.jedis.params.ZIncrByParams; -import com.fr.third.redis.clients.jedis.params.LPosParams; import java.util.List; import java.util.Map; @@ -48,15 +28,7 @@ public interface RedisPipeline { 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 expire(String key, int seconds); Response pexpire(String key, long milliseconds); @@ -66,10 +38,6 @@ public interface RedisPipeline { 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); @@ -102,12 +70,6 @@ public interface RedisPipeline { 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); @@ -120,14 +82,6 @@ public interface RedisPipeline { 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); @@ -146,8 +100,6 @@ public interface RedisPipeline { Response rpop(String key); - Response> rpop(String key, int count); - Response rpush(String key, String... string); Response rpushx(String key, String... string); @@ -158,21 +110,11 @@ public interface RedisPipeline { 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 setex(String key, int seconds, String value); Response setnx(String key, String value); @@ -212,8 +154,6 @@ public interface RedisPipeline { 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); @@ -236,7 +176,8 @@ public interface RedisPipeline { Response> zrangeByScoreWithScores(String key, double min, double max); - Response> zrangeByScoreWithScores(String key, double min, double max, int offset, int count); + Response> zrangeByScoreWithScores(String key, double min, double max, int offset, + int count); Response> zrevrangeByScore(String key, double max, double min); @@ -250,18 +191,14 @@ public interface RedisPipeline { Response> zrevrangeByScoreWithScores(String key, String max, String min); - Response> zrevrangeByScoreWithScores(String key, double max, double min, 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> 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); @@ -280,25 +217,17 @@ public interface RedisPipeline { 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> 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> zrevrangeByLex(String key, String max, String min, + int offset, int count); Response zremrangeByLex(String key, String min, String max); @@ -309,47 +238,17 @@ public interface RedisPipeline { 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 #restoreReplace(java.lang.String, long, byte[])}. - */ - @Deprecated - default Response restoreReplace(String key, int ttl, byte[] serializedValue) { - return restoreReplace(key, (long) ttl, serializedValue); - } - - 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); @@ -359,100 +258,14 @@ public interface RedisPipeline { 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); + 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); + 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); + 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 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); + GeoUnit unit, GeoRadiusParam param); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisAccessControlException.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisAccessControlException.java deleted file mode 100644 index 7b015de7e..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisAccessControlException.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.fr.third.redis.clients.jedis.exceptions; - -public class JedisAccessControlException extends JedisDataException { - - public JedisAccessControlException(String message) { - super(message); - } - - public JedisAccessControlException(Throwable cause) { - super(cause); - } - - public JedisAccessControlException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisBusyException.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisBusyException.java index e40254c07..10c8c2e44 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisBusyException.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisBusyException.java @@ -2,18 +2,18 @@ package com.fr.third.redis.clients.jedis.exceptions; public class JedisBusyException extends JedisDataException { - private static final long serialVersionUID = 3992655220229243478L; + private static final long serialVersionUID = 3992655220229243478L; - public JedisBusyException(final String message) { - super(message); - } + public JedisBusyException(final String message) { + super(message); + } - public JedisBusyException(final Throwable cause) { - super(cause); - } + public JedisBusyException(final Throwable cause) { + super(cause); + } - public JedisBusyException(final String message, final Throwable cause) { - super(message, cause); - } + public JedisBusyException(final String message, final Throwable cause) { + super(message, cause); + } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisNoReachableClusterNodeException.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisNoReachableClusterNodeException.java index 38453d452..b40a36575 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisNoReachableClusterNodeException.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisNoReachableClusterNodeException.java @@ -1,8 +1,5 @@ package com.fr.third.redis.clients.jedis.exceptions; -/** - * WARNING: This exception will extend {@link JedisClusterOperationException} in upcoming major release. - */ public class JedisNoReachableClusterNodeException extends JedisConnectionException { private static final long serialVersionUID = 3878122572474110407L; diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisNoScriptException.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisNoScriptException.java index 521fd11cc..064b5fd0d 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisNoScriptException.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisNoScriptException.java @@ -1,17 +1,11 @@ package com.fr.third.redis.clients.jedis.exceptions; -public class JedisNoScriptException extends JedisDataException { +public class JedisNoScriptException extends JedisDataException { private static final long serialVersionUID = 4674378093072060731L; - public JedisNoScriptException(final String message) { - super(message); - } + public JedisNoScriptException(final String message) { super(message); } - public JedisNoScriptException(final Throwable cause) { - super(cause); - } + public JedisNoScriptException(final Throwable cause) { super(cause); } - public JedisNoScriptException(final String message, final Throwable cause) { - super(message, cause); - } + public JedisNoScriptException(final String message, final Throwable cause) { super(message, cause); } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisRedirectionException.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisRedirectionException.java index 922e7eca7..ef54e4ead 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisRedirectionException.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/exceptions/JedisRedirectionException.java @@ -5,8 +5,8 @@ import com.fr.third.redis.clients.jedis.HostAndPort; public class JedisRedirectionException extends JedisDataException { private static final long serialVersionUID = 3878126572474819403L; - private final HostAndPort targetNode; - private final int slot; + private HostAndPort targetNode; + private int slot; public JedisRedirectionException(String message, HostAndPort targetNode, int slot) { super(message); diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/ClientKillParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/ClientKillParams.java deleted file mode 100644 index 990bd6050..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/ClientKillParams.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.fr.third.redis.clients.jedis.params; - -public class ClientKillParams extends Params { - - private static final String ID = "ID"; - private static final String TYPE = "TYPE"; - private static final String ADDR = "ADDR"; - private static final String SKIPME = "SKIPME"; - private static final String USER = "USER"; - private static final String LADDR = "LADDR"; - - public static enum Type { - NORMAL, MASTER, SLAVE, PUBSUB; - } - - public static enum SkipMe { - YES, NO; - } - - public ClientKillParams() { - } - - public static ClientKillParams clientKillParams() { - return new ClientKillParams(); - } - - public ClientKillParams id(String clientId) { - addParam(ID, clientId); - return this; - } - - public ClientKillParams id(byte[] clientId) { - addParam(ID, clientId); - return this; - } - - public ClientKillParams type(Type type) { - addParam(TYPE, type); - return this; - } - - public ClientKillParams addr(String ipPort) { - addParam(ADDR, ipPort); - return this; - } - - public ClientKillParams addr(byte[] ipPort) { - addParam(ADDR, ipPort); - return this; - } - - public ClientKillParams addr(String ip, int port) { - addParam(ADDR, ip + ':' + port); - return this; - } - - public ClientKillParams skipMe(SkipMe skipMe) { - addParam(SKIPME, skipMe); - return this; - } - - public ClientKillParams user(String username) { - addParam(USER, username); - return this; - } - - public ClientKillParams laddr(String ipPort) { - addParam(LADDR, ipPort); - return this; - } - - public ClientKillParams laddr(String ip, int port) { - addParam(LADDR, ip + ':' + port); - return this; - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/GeoAddParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/GeoAddParams.java deleted file mode 100644 index d4e1fab1d..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/GeoAddParams.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.fr.third.redis.clients.jedis.params; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import com.fr.third.redis.clients.jedis.util.SafeEncoder; - -public class GeoAddParams extends Params { - - private static final String NX = "nx"; - private static final String XX = "xx"; - private static final String CH = "ch"; - - public GeoAddParams() { - } - - public static GeoAddParams geoAddParams() { - return new GeoAddParams(); - } - - /** - * Don't update already existing elements. Always add new elements. - * @return GetExParams - */ - public GeoAddParams nx() { - addParam(NX); - return this; - } - - /** - * Only update elements that already exist. Never add elements. - * @return GetExParams - */ - public GeoAddParams xx() { - addParam(XX); - return this; - } - - /** - * Modify the return value from the number of new elements added, to the total number of elements - * changed - * @return GetExParams - */ - public GeoAddParams ch() { - addParam(CH); - 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)); - } - - if (contains(CH)) { - byteParams.add(SafeEncoder.encode(CH)); - } - - Collections.addAll(byteParams, args); - - return byteParams.toArray(new byte[byteParams.size()][]); - } - -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/GeoRadiusParam.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/GeoRadiusParam.java index 115ae5678..5bf92d575 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/GeoRadiusParam.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/GeoRadiusParam.java @@ -4,12 +4,13 @@ import com.fr.third.redis.clients.jedis.Protocol; import com.fr.third.redis.clients.jedis.util.SafeEncoder; import java.util.ArrayList; -import java.util.Collections; public class GeoRadiusParam extends Params { private static final String WITHCOORD = "withcoord"; private static final String WITHDIST = "withdist"; - private static final String WITHHASH = "withhash"; + + // Do not add WITHHASH since we can't classify result of WITHHASH and WITHDIST, + // and WITHHASH is for debugging purposes private static final String ASC = "asc"; private static final String DESC = "desc"; @@ -32,11 +33,6 @@ public class GeoRadiusParam extends Params { return this; } - public GeoRadiusParam withHash() { - addParam(WITHHASH); - return this; - } - public GeoRadiusParam sortAscending() { addParam(ASC); return this; @@ -55,8 +51,10 @@ public class GeoRadiusParam extends Params { } public byte[][] getByteParams(byte[]... args) { - ArrayList byteParams = new ArrayList<>(); - Collections.addAll(byteParams, args); + ArrayList byteParams = new ArrayList(); + for (byte[] arg : args) { + byteParams.add(arg); + } if (contains(WITHCOORD)) { byteParams.add(SafeEncoder.encode(WITHCOORD)); @@ -64,13 +62,10 @@ public class GeoRadiusParam extends Params { if (contains(WITHDIST)) { byteParams.add(SafeEncoder.encode(WITHDIST)); } - if (contains(WITHHASH)) { - byteParams.add(SafeEncoder.encode(WITHHASH)); - } if (contains(COUNT)) { byteParams.add(SafeEncoder.encode(COUNT)); - byteParams.add(Protocol.toByteArray((int) getParam(COUNT))); + byteParams.add(Protocol.toByteArray((Integer) getParam(COUNT))); } if (contains(ASC)) { diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/GeoRadiusStoreParam.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/GeoRadiusStoreParam.java deleted file mode 100644 index 558ef6423..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/GeoRadiusStoreParam.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.fr.third.redis.clients.jedis.params; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -import com.fr.third.redis.clients.jedis.util.SafeEncoder; - -public class GeoRadiusStoreParam extends Params { - private static final String STORE = "store"; - private static final String STOREDIST = "storedist"; - - public GeoRadiusStoreParam() { - } - - public static GeoRadiusStoreParam geoRadiusStoreParam() { - return new GeoRadiusStoreParam(); - } - - public GeoRadiusStoreParam store(String key) { - if (key != null) { - addParam(STORE, key); - } - return this; - } - - public GeoRadiusStoreParam storeDist(String key) { - if (key != null) { - addParam(STOREDIST, key); - } - return this; - } - - /** - * WARNING: In Redis, if STOREDIST exists, store will be ignored. - *

        - * Refer: https://github.com/antirez/redis/blob/6.0/src/geo.c#L649 - * - * @return STORE or STOREDIST - */ - public byte[] getOption() { - if (contains(STOREDIST)) { - return SafeEncoder.encode(STOREDIST); - } - - 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/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/GetExParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/GetExParams.java deleted file mode 100644 index 64d52d737..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/GetExParams.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.fr.third.redis.clients.jedis.params; - -import java.util.ArrayList; -import java.util.Collections; - -import com.fr.third.redis.clients.jedis.Protocol; -import com.fr.third.redis.clients.jedis.util.SafeEncoder; - -public class GetExParams extends Params { - - private static final String PX = "px"; - private static final String EX = "ex"; - private static final String EXAT = "exat"; - private static final String PXAT = "pxat"; - private static final String PERSIST = "persist"; - - public GetExParams() { - } - - public static GetExParams getExParams() { - return new GetExParams(); - } - - /** - * Set the specified expire time, in seconds. - * @return GetExParams - */ - public GetExParams ex(long secondsToExpire) { - addParam(EX, secondsToExpire); - return this; - } - - /** - * Set the specified expire time, in milliseconds. - * @return GetExParams - */ - public GetExParams px(long millisecondsToExpire) { - addParam(PX, millisecondsToExpire); - return this; - } - - /** - * Set the specified Unix time at which the key will expire, in seconds. - * @param seconds - * @return GetExParams - */ - public GetExParams exAt(long seconds) { - addParam(EXAT, seconds); - return this; - } - - /** - * Set the specified Unix time at which the key will expire, in milliseconds. - * @param milliseconds - * @return GetExParams - */ - public GetExParams pxAt(long milliseconds) { - addParam(PXAT, milliseconds); - return this; - } - - /** - * Remove the time to live associated with the key. - * @return GetExParams - */ - public GetExParams persist() { - addParam(PERSIST); - return this; - } - - public byte[][] getByteParams(byte[] key, byte[]... args) { - ArrayList byteParams = new ArrayList<>(); - byteParams.add(key); - - if (contains(EX)) { - byteParams.add(SafeEncoder.encode(EX)); - byteParams.add(Protocol.toByteArray((long) getParam(EX))); - } else if (contains(PX)) { - byteParams.add(SafeEncoder.encode(PX)); - byteParams.add(Protocol.toByteArray((long) getParam(PX))); - } else if (contains(EXAT)) { - byteParams.add(SafeEncoder.encode(EXAT)); - byteParams.add(Protocol.toByteArray((long) getParam(EXAT))); - } else if (contains(PXAT)) { - byteParams.add(SafeEncoder.encode(PXAT)); - byteParams.add(Protocol.toByteArray((long) getParam(PXAT))); - } else if (contains(PERSIST)) { - byteParams.add(SafeEncoder.encode(PERSIST)); - } - - Collections.addAll(byteParams, args); - - return byteParams.toArray(new byte[byteParams.size()][]); - } - -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/LPosParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/LPosParams.java deleted file mode 100644 index f118c51a0..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/LPosParams.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.fr.third.redis.clients.jedis.params; - -import java.util.ArrayList; -import java.util.Collections; - -import com.fr.third.redis.clients.jedis.Protocol; -import com.fr.third.redis.clients.jedis.util.SafeEncoder; - -public class LPosParams extends Params { - - private static final String RANK = "RANK"; - private static final String MAXLEN = "MAXLEN"; - - public static LPosParams lPosParams() { - return new LPosParams(); - } - - public LPosParams rank(int rank) { - addParam(RANK, rank); - return this; - } - - public LPosParams maxlen(int maxLen) { - addParam(MAXLEN, maxLen); - return this; - } - - public byte[][] getByteParams(byte[]... args) { - ArrayList byteParams = new ArrayList<>(); - Collections.addAll(byteParams, args); - - if (contains(RANK)) { - byteParams.add(SafeEncoder.encode(RANK)); - byteParams.add(Protocol.toByteArray((int) getParam(RANK))); - } - - if (contains(MAXLEN)) { - byteParams.add(SafeEncoder.encode(MAXLEN)); - byteParams.add(Protocol.toByteArray((int) getParam(MAXLEN))); - } - - return byteParams.toArray(new byte[byteParams.size()][]); - } - -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/MigrateParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/MigrateParams.java deleted file mode 100644 index a6c58f23b..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/MigrateParams.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.fr.third.redis.clients.jedis.params; - -import com.fr.third.redis.clients.jedis.util.SafeEncoder; - -import java.util.ArrayList; -import java.util.List; - -public class MigrateParams extends Params { - - private static final String COPY = "COPY"; - private static final String REPLACE = "REPLACE"; - private static final String AUTH = "AUTH"; - private static final String AUTH2 = "AUTH2"; - - public MigrateParams() { - } - - public static MigrateParams migrateParams() { - return new MigrateParams(); - } - - public MigrateParams copy() { - addParam(COPY); - return this; - } - - public MigrateParams replace() { - addParam(REPLACE); - return this; - } - - public MigrateParams auth(String password) { - addParam(AUTH, password); - return this; - } - - public MigrateParams auth2(String username, String password) { - addParam(AUTH2, new String[] { username, password }); - return this; - } - - @Override - public byte[][] getByteParams() { - List byteParams = new ArrayList<>(); - - if (contains(COPY)) { - byteParams.add(SafeEncoder.encode(COPY)); - } - if (contains(REPLACE)) { - byteParams.add(SafeEncoder.encode(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])); - } - - return byteParams.toArray(new byte[byteParams.size()][]); - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/Params.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/Params.java index d40fbb277..b0222052d 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/Params.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/Params.java @@ -5,7 +5,6 @@ import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; -import com.fr.third.redis.clients.jedis.Protocol; import com.fr.third.redis.clients.jedis.util.SafeEncoder; public abstract class Params { @@ -20,27 +19,12 @@ public abstract class Params { } public byte[][] getByteParams() { - if (params == null) return new byte[0][]; - ArrayList byteParams = new ArrayList<>(); + ArrayList byteParams = new ArrayList(); for (Entry param : params.entrySet()) { byteParams.add(SafeEncoder.encode(param.getKey())); - - Object value = param.getValue(); - if (value != null) { - if (value instanceof byte[]) { - byteParams.add((byte[]) value); - } else if (value instanceof Boolean) { - byteParams.add(Protocol.toByteArray((boolean) value)); - } else if (value instanceof Integer) { - byteParams.add(Protocol.toByteArray((int) value)); - } else if (value instanceof Long) { - byteParams.add(Protocol.toByteArray((long) value)); - } else if (value instanceof Double) { - byteParams.add(Protocol.toByteArray((double) value)); - } else { - byteParams.add(SafeEncoder.encode(String.valueOf(value))); - } + if (param.getValue() != null) { + byteParams.add(SafeEncoder.encode(String.valueOf(param.getValue()))); } } @@ -55,30 +39,16 @@ public abstract class Params { protected void addParam(String name, Object value) { if (params == null) { - params = new HashMap<>(); + params = new HashMap(); } params.put(name, value); } protected void addParam(String name) { if (params == null) { - params = new HashMap<>(); + params = new HashMap(); } params.put(name, null); } - @Override - public String toString() { - ArrayList paramsFlatList = new ArrayList<>(); - if (params != null) { - for (Entry param : params.entrySet()) { - paramsFlatList.add(param.getKey()); - Object value = param.getValue(); - if (value != null) { - paramsFlatList.add(SafeEncoder.encodeObject(value)); - } - } - } - return paramsFlatList.toString(); - } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/RestoreParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/RestoreParams.java deleted file mode 100644 index e6673143a..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/RestoreParams.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.fr.third.redis.clients.jedis.params; - -import static com.fr.third.redis.clients.jedis.Protocol.Keyword.ABSTTL; -import static com.fr.third.redis.clients.jedis.Protocol.Keyword.FREQ; -import static com.fr.third.redis.clients.jedis.Protocol.Keyword.IDLETIME; -import static com.fr.third.redis.clients.jedis.Protocol.Keyword.REPLACE; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import com.fr.third.redis.clients.jedis.Protocol; - -public class RestoreParams extends Params { - - private boolean replace; - - private boolean absTtl; - - private Long idleTime; - - private Long frequency; - - public static RestoreParams restoreParams() { - return new RestoreParams(); - } - - public RestoreParams replace() { - this.replace = true; - return this; - } - - public RestoreParams absTtl() { - this.absTtl = true; - return this; - } - - public RestoreParams idleTime(long idleTime) { - this.idleTime = idleTime; - return this; - } - - public RestoreParams frequency(long frequency) { - this.frequency = frequency; - return this; - } - - public byte[][] getByteParams(byte[] key, byte[]... args) { - List byteParams = new ArrayList<>(); - byteParams.add(key); - Collections.addAll(byteParams, args); - - if (replace) { - byteParams.add(REPLACE.getRaw()); - } - - if (absTtl) { - byteParams.add(ABSTTL.getRaw()); - } - - if (idleTime != null) { - byteParams.add(IDLETIME.getRaw()); - byteParams.add(Protocol.toByteArray(idleTime)); - } - - if (frequency != null) { - byteParams.add(FREQ.getRaw()); - byteParams.add(Protocol.toByteArray(frequency)); - } - return byteParams.toArray(new byte[byteParams.size()][]); - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/SetParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/SetParams.java index 8fc9995f3..c72765a01 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/SetParams.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/SetParams.java @@ -1,9 +1,7 @@ package com.fr.third.redis.clients.jedis.params; import java.util.ArrayList; -import java.util.Collections; -import com.fr.third.redis.clients.jedis.Protocol; import com.fr.third.redis.clients.jedis.util.SafeEncoder; public class SetParams extends Params { @@ -12,10 +10,6 @@ public class SetParams extends Params { private static final String NX = "nx"; private static final String PX = "px"; private static final String EX = "ex"; - private static final String EXAT = "exat"; - private static final String PXAT = "pxat"; - private static final String KEEPTTL = "keepttl"; - private static final String GET = "get"; public SetParams() { } @@ -28,19 +22,8 @@ public class SetParams extends Params { * Set the specified expire time, in seconds. * @param secondsToExpire * @return SetParams - * @deprecated Use {@link #ex(long)}. */ - @Deprecated public SetParams ex(int secondsToExpire) { - return ex((long) secondsToExpire); - } - - /** - * Set the specified expire time, in seconds. - * @param secondsToExpire - * @return SetParams - */ - public SetParams ex(long secondsToExpire) { addParam(EX, secondsToExpire); return this; } @@ -73,47 +56,11 @@ public class SetParams extends Params { return this; } - /** - * Set the specified Unix time at which the key will expire, in seconds. - * @param seconds - * @return SetParams - */ - public SetParams exAt(long seconds) { - addParam(EXAT, seconds); - return this; - } - - /** - * Set the specified Unix time at which the key will expire, in milliseconds. - * @param milliseconds - * @return SetParams - */ - public SetParams pxAt(long milliseconds) { - addParam(PXAT, milliseconds); - return this; - } - - /** - * Retain the time to live associated with the key. - * @return SetParams - */ - public SetParams keepttl() { - addParam(KEEPTTL); - return this; - } - - /** - * Return the old value stored at key, or nil when key did not exist. - * @return SetParams - */ - public SetParams get() { - addParam(GET); - return this; - } - public byte[][] getByteParams(byte[]... args) { - ArrayList byteParams = new ArrayList<>(); - Collections.addAll(byteParams, args); + ArrayList byteParams = new ArrayList(); + for (byte[] arg : args) { + byteParams.add(arg); + } if (contains(NX)) { byteParams.add(SafeEncoder.encode(NX)); @@ -124,26 +71,11 @@ public class SetParams extends Params { if (contains(EX)) { byteParams.add(SafeEncoder.encode(EX)); - byteParams.add(Protocol.toByteArray((long) getParam(EX))); + byteParams.add(SafeEncoder.encode(String.valueOf(getParam(EX)))); } if (contains(PX)) { byteParams.add(SafeEncoder.encode(PX)); - byteParams.add(Protocol.toByteArray((long) getParam(PX))); - } - if (contains(EXAT)) { - byteParams.add(SafeEncoder.encode(EXAT)); - byteParams.add(Protocol.toByteArray((long) getParam(EXAT))); - } - if (contains(PXAT)) { - byteParams.add(SafeEncoder.encode(PXAT)); - byteParams.add(Protocol.toByteArray((long) getParam(PXAT))); - } - if (contains(KEEPTTL)) { - byteParams.add(SafeEncoder.encode(KEEPTTL)); - } - - if (contains(GET)) { - byteParams.add(SafeEncoder.encode(GET)); + byteParams.add(SafeEncoder.encode(String.valueOf(getParam(PX)))); } return byteParams.toArray(new byte[byteParams.size()][]); diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XAddParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XAddParams.java deleted file mode 100644 index 0bb421bbc..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XAddParams.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.fr.third.redis.clients.jedis.params; - -import static com.fr.third.redis.clients.jedis.Protocol.Keyword.LIMIT; -import static com.fr.third.redis.clients.jedis.Protocol.Keyword.MAXLEN; -import static com.fr.third.redis.clients.jedis.Protocol.Keyword.MINID; -import static com.fr.third.redis.clients.jedis.Protocol.Keyword.NOMKSTREAM; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import com.fr.third.redis.clients.jedis.Protocol; -import com.fr.third.redis.clients.jedis.util.SafeEncoder; - -public class XAddParams extends Params { - - private String id; - - private Long maxLen; - - private boolean approximateTrimming; - - private boolean exactTrimming; - - private boolean nomkstream; - - private String minId; - - private Long limit; - - public static XAddParams xAddParams() { - return new XAddParams(); - } - - public XAddParams noMkStream() { - this.nomkstream = true; - return this; - } - - public XAddParams id(String id) { - this.id = id; - return this; - } - - public XAddParams maxLen(long maxLen) { - this.maxLen = maxLen; - return this; - } - - public XAddParams minId(String minId) { - this.minId = minId; - return this; - } - - public XAddParams approximateTrimming() { - this.approximateTrimming = true; - return this; - } - - public XAddParams exactTrimming() { - this.exactTrimming = true; - return this; - } - - public XAddParams limit(long limit) { - this.limit = limit; - return this; - } - - public byte[][] getByteParams(byte[] key, byte[]... args) { - List byteParams = new ArrayList<>(); - byteParams.add(key); - - if (nomkstream) { - byteParams.add(NOMKSTREAM.getRaw()); - } - if (maxLen != null) { - byteParams.add(MAXLEN.getRaw()); - - if (approximateTrimming) { - byteParams.add(Protocol.BYTES_TILDE); - } else if (exactTrimming) { - byteParams.add(Protocol.BYTES_EQUAL); - } - - byteParams.add(Protocol.toByteArray(maxLen)); - } else if (minId != null) { - byteParams.add(MINID.getRaw()); - - if (approximateTrimming) { - byteParams.add(Protocol.BYTES_TILDE); - } else if (exactTrimming) { - byteParams.add(Protocol.BYTES_EQUAL); - } - - byteParams.add(SafeEncoder.encode(minId)); - } - - if (limit != null) { - byteParams.add(LIMIT.getRaw()); - byteParams.add(Protocol.toByteArray(limit)); - } - - if (id != null) { - byteParams.add(SafeEncoder.encode(id)); - } else { - byteParams.add(Protocol.BYTES_ASTERISK); - } - - Collections.addAll(byteParams, args); - return byteParams.toArray(new byte[byteParams.size()][]); - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XClaimParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XClaimParams.java deleted file mode 100644 index 850b88f64..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XClaimParams.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.fr.third.redis.clients.jedis.params; - -public class XClaimParams extends Params { - - private static final String IDLE = "IDLE"; - private static final String TIME = "TIME"; - private static final String RETRYCOUNT = "RETRYCOUNT"; - private static final String FORCE = "FORCE"; - - public XClaimParams() { - } - - public static XClaimParams xClaimParams() { - return new XClaimParams(); - } - - /** - * Set the idle time (last time it was delivered) of the message. - * @param idleTime - * @return XClaimParams - */ - public XClaimParams idle(long idleTime) { - addParam(IDLE, idleTime); - return this; - } - - /** - * Set the idle time to a specific Unix time (in milliseconds). - * @param idleUnixTime - * @return XClaimParams - */ - public XClaimParams time(long idleUnixTime) { - addParam(TIME, idleUnixTime); - return this; - } - - /** - * Set the retry counter to the specified value. - * @param count - * @return XClaimParams - */ - public XClaimParams retryCount(int count) { - addParam(RETRYCOUNT, count); - return this; - } - - /** - * Creates the pending message entry in the PEL even if certain specified IDs are not already in - * the PEL assigned to a different client. - * @return XClaimParams - */ - public XClaimParams force() { - addParam(FORCE); - return this; - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XPendingParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XPendingParams.java deleted file mode 100644 index a28ca77f1..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XPendingParams.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.fr.third.redis.clients.jedis.params; - -import static com.fr.third.redis.clients.jedis.Protocol.Keyword.IDLE; - -import java.util.ArrayList; -import java.util.List; - -import com.fr.third.redis.clients.jedis.Protocol; -import com.fr.third.redis.clients.jedis.StreamEntryID; -import com.fr.third.redis.clients.jedis.util.SafeEncoder; - -public class XPendingParams extends Params { - - private Long idle; - - private String consumer; - - private StreamEntryID start; - - private StreamEntryID end; - - private Integer count; - - public static XPendingParams xPendingParams() { - return new XPendingParams(); - } - - public XPendingParams idle(long idle) { - this.idle = idle; - return this; - } - - public XPendingParams start(StreamEntryID start) { - this.start = start; - return this; - } - - public XPendingParams end(StreamEntryID end) { - this.end = end; - return this; - } - - public XPendingParams count(int count) { - this.count = count; - return this; - } - - public XPendingParams consumer(String consumer) { - this.consumer = consumer; - return this; - } - - @Override - public byte[][] getByteParams() { - List byteParams = new ArrayList<>(); - - if (idle != null) { - byteParams.add(IDLE.getRaw()); - byteParams.add(Protocol.toByteArray(idle)); - } - - if (start == null) { - byteParams.add(SafeEncoder.encode("-")); - } else { - byteParams.add(SafeEncoder.encode(start.toString())); - } - - if (end == null) { - byteParams.add(SafeEncoder.encode("+")); - } else { - byteParams.add(SafeEncoder.encode(end.toString())); - } - - if (count != null) { - byteParams.add(Protocol.toByteArray(count)); - } - - if (consumer != null) { - byteParams.add(SafeEncoder.encode(consumer)); - } - return byteParams.toArray(new byte[byteParams.size()][]); - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XReadGroupParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XReadGroupParams.java deleted file mode 100644 index 01ac2a6a7..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XReadGroupParams.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.fr.third.redis.clients.jedis.params; - -public class XReadGroupParams extends Params { - - private static final String COUNT = "COUNT"; - private static final String BLOCK = "BLOCK"; - private static final String NOACK = "NOACK"; - - public static XReadGroupParams xReadGroupParams() { - return new XReadGroupParams(); - } - - public XReadGroupParams count(int count) { - addParam(COUNT, count); - return this; - } - - public XReadGroupParams block(int block) { - addParam(BLOCK, block); - return this; - } - - public XReadGroupParams noAck() { - addParam(NOACK); - return this; - } - - public boolean hasBlock() { - return super.contains(BLOCK); - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XReadParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XReadParams.java deleted file mode 100644 index 808621d38..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XReadParams.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.fr.third.redis.clients.jedis.params; - -public class XReadParams extends Params { - - private static final String COUNT = "COUNT"; - private static final String BLOCK = "BLOCK"; - - public static XReadParams xReadParams() { - return new XReadParams(); - } - - public XReadParams count(int count) { - addParam(COUNT, count); - return this; - } - - public XReadParams block(int block) { - addParam(BLOCK, block); - return this; - } - - public boolean hasBlock() { - return super.contains(BLOCK); - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XTrimParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XTrimParams.java deleted file mode 100644 index 8b6710f66..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/XTrimParams.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.fr.third.redis.clients.jedis.params; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import com.fr.third.redis.clients.jedis.Protocol; -import com.fr.third.redis.clients.jedis.util.SafeEncoder; - -import static com.fr.third.redis.clients.jedis.Protocol.Keyword.LIMIT; -import static com.fr.third.redis.clients.jedis.Protocol.Keyword.MAXLEN; -import static com.fr.third.redis.clients.jedis.Protocol.Keyword.MINID; - -public class XTrimParams extends Params { - - private Long maxLen; - - private boolean approximateTrimming; - - private boolean exactTrimming; - - private String minId; - - private Long limit; - - public static XTrimParams xTrimParams() { - return new XTrimParams(); - } - - - public XTrimParams maxLen(long maxLen) { - this.maxLen = maxLen; - return this; - } - - public XTrimParams minId(String minId) { - this.minId = minId; - return this; - } - - public XTrimParams approximateTrimming() { - this.approximateTrimming = true; - return this; - } - - public XTrimParams exactTrimming() { - this.exactTrimming = true; - return this; - } - - public XTrimParams limit(long limit) { - this.limit = limit; - return this; - } - - public byte[][] getByteParams(byte[] key, byte[]... args) { - List byteParams = new ArrayList<>(); - byteParams.add(key); - - if (maxLen != null) { - byteParams.add(MAXLEN.getRaw()); - - if (approximateTrimming) { - byteParams.add(Protocol.BYTES_TILDE); - } else if (exactTrimming) { - byteParams.add(Protocol.BYTES_EQUAL); - } - - byteParams.add(Protocol.toByteArray(maxLen)); - } else if (minId != null) { - byteParams.add(MINID.getRaw()); - - if (approximateTrimming) { - byteParams.add(Protocol.BYTES_TILDE); - } else if (exactTrimming) { - byteParams.add(Protocol.BYTES_EQUAL); - } - - byteParams.add(SafeEncoder.encode(minId)); - } - - if (limit != null) { - byteParams.add(LIMIT.getRaw()); - byteParams.add(Protocol.toByteArray(limit)); - } - - Collections.addAll(byteParams, args); - return byteParams.toArray(new byte[byteParams.size()][]); - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/ZAddParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/ZAddParams.java index 8a3868c6c..7573bc766 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/ZAddParams.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/ZAddParams.java @@ -3,15 +3,12 @@ package com.fr.third.redis.clients.jedis.params; import com.fr.third.redis.clients.jedis.util.SafeEncoder; import java.util.ArrayList; -import java.util.Collections; public class ZAddParams extends Params { private static final String XX = "xx"; private static final String NX = "nx"; private static final String CH = "ch"; - private static final String LT = "lt"; - private static final String GT = "gt"; public ZAddParams() { } @@ -48,26 +45,8 @@ public class ZAddParams extends Params { return this; } - /** - * Only update existing elements if the new score is greater than the current score. - * @return ZAddParams - */ - public ZAddParams gt() { - addParam(GT); - return this; - } - - /** - * Only update existing elements if the new score is less than the current score. - * @return ZAddParams - */ - public ZAddParams lt() { - addParam(LT); - return this; - } - public byte[][] getByteParams(byte[] key, byte[]... args) { - ArrayList byteParams = new ArrayList<>(); + ArrayList byteParams = new ArrayList(); byteParams.add(key); if (contains(NX)) { @@ -79,14 +58,10 @@ public class ZAddParams extends Params { if (contains(CH)) { byteParams.add(SafeEncoder.encode(CH)); } - if (contains(LT)) { - byteParams.add(SafeEncoder.encode(LT)); - } - if (contains(GT)) { - byteParams.add(SafeEncoder.encode(GT)); - } - Collections.addAll(byteParams, args); + for (byte[] arg : args) { + byteParams.add(arg); + } return byteParams.toArray(new byte[byteParams.size()][]); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/ZIncrByParams.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/ZIncrByParams.java index 9c69a0471..63c2831a9 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/ZIncrByParams.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/params/ZIncrByParams.java @@ -3,7 +3,6 @@ package com.fr.third.redis.clients.jedis.params; import com.fr.third.redis.clients.jedis.util.SafeEncoder; import java.util.ArrayList; -import java.util.Collections; /** * Parameters for ZINCRBY commands
        @@ -51,7 +50,7 @@ public class ZIncrByParams extends Params { } public byte[][] getByteParams(byte[] key, byte[]... args) { - ArrayList byteParams = new ArrayList<>(); + ArrayList byteParams = new ArrayList(); byteParams.add(key); if (contains(NX)) { @@ -63,7 +62,10 @@ public class ZIncrByParams extends Params { byteParams.add(SafeEncoder.encode(INCR)); - Collections.addAll(byteParams, args); + for (byte[] arg : args) { + byteParams.add(arg); + } + return byteParams.toArray(new byte[byteParams.size()][]); } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/resps/KeyedListElement.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/resps/KeyedListElement.java deleted file mode 100644 index 2f1d1640e..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/resps/KeyedListElement.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.fr.third.redis.clients.jedis.resps; - -import com.fr.third.redis.clients.jedis.util.SafeEncoder; - -/** - * This class is used to represent a List element when it is returned with respective key name. - */ -public class KeyedListElement { - - private final String key; - private final String element; - - public KeyedListElement(byte[] key, byte[] element) { - this(SafeEncoder.encode(key), SafeEncoder.encode(element)); - } - - public KeyedListElement(String key, String element) { - this.key = key; - this.element = element; - } - - public String getKey() { - return key; - } - - public String getElement() { - return element; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof KeyedZSetElement)) return false; - - KeyedListElement other = (KeyedListElement) o; - return key.equals(other.key) && element.equals(other.element); - } - - @Override - public int hashCode() { - return 31 * key.hashCode() + element.hashCode(); - } - - @Override - public String toString() { - return "KeyedListElement{" + "key=" + key + ", element='" + element + "} "; - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/resps/KeyedZSetElement.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/resps/KeyedZSetElement.java deleted file mode 100644 index b7a9d0593..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/resps/KeyedZSetElement.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.fr.third.redis.clients.jedis.resps; - -import com.fr.third.redis.clients.jedis.Tuple; -import com.fr.third.redis.clients.jedis.util.SafeEncoder; - -/** - * This class is used to represent a SortedSet element when it is returned with respective key name. - */ -public class KeyedZSetElement extends Tuple { - - private final String key; - - public KeyedZSetElement(byte[] key, byte[] element, Double score) { - super(element, score); - this.key = SafeEncoder.encode(key); - } - - public KeyedZSetElement(String key, String element, Double score) { - super(element, score); - this.key = key; - } - - public String getKey() { - return key; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof KeyedZSetElement)) return false; - - if (!key.equals(((KeyedZSetElement) o).key)) return false; - return super.equals(o); - } - - @Override - public int hashCode() { - return 31 * key.hashCode() + super.hashCode(); - } - - @Override - public String toString() { - return "KeyedZSetElement{" + "key=" + key + ", element='" + getElement() + "'" - + ", score=" + getScore() + "} "; - } -} diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/resps/package-info.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/resps/package-info.java deleted file mode 100644 index 8e8f66238..000000000 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/resps/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/* - * This package contains the classes that represent different Redis responses. - */ -package com.fr.third.redis.clients.jedis.resps; diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/ByteArrayComparator.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/ByteArrayComparator.java index f10b14721..171736477 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/ByteArrayComparator.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/ByteArrayComparator.java @@ -2,7 +2,7 @@ package com.fr.third.redis.clients.jedis.util; public final class ByteArrayComparator { private ByteArrayComparator() { - throw new InstantiationError("Must not instantiate this class"); + throw new InstantiationError( "Must not instantiate this class" ); } public static int compare(final byte[] val1, final byte[] val2) { @@ -13,12 +13,12 @@ public final class ByteArrayComparator { for (int i = 0; i < lmin; i++) { byte b1 = val1[i]; byte b2 = val2[i]; - if (b1 < b2) return -1; - if (b1 > b2) return 1; + if(b1 < b2) return -1; + if(b1 > b2) return 1; } - if (len1 < len2) return -1; - if (len1 > len2) return 1; + if(len1 < len2) return -1; + if(len1 > len2) return 1; return 0; } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Hashing.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Hashing.java index 4b2c75402..6068f4c66 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Hashing.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Hashing.java @@ -5,7 +5,7 @@ import java.security.NoSuchAlgorithmException; public interface Hashing { Hashing MURMUR_HASH = new MurmurHash(); - ThreadLocal md5Holder = new ThreadLocal<>(); + ThreadLocal md5Holder = new ThreadLocal(); Hashing MD5 = new Hashing() { @Override @@ -27,8 +27,9 @@ public interface Hashing { md5.reset(); md5.update(key); byte[] bKey = md5.digest(); - return ((long) (bKey[3] & 0xFF) << 24) | ((long) (bKey[2] & 0xFF) << 16) + long res = ((long) (bKey[3] & 0xFF) << 24) | ((long) (bKey[2] & 0xFF) << 16) | ((long) (bKey[1] & 0xFF) << 8) | (long) (bKey[0] & 0xFF); + return res; } }; diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/JedisByteHashMap.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/JedisByteHashMap.java index 58621b22f..741514fca 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/JedisByteHashMap.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/JedisByteHashMap.java @@ -11,7 +11,7 @@ import java.util.Set; public class JedisByteHashMap implements Map, Cloneable, Serializable { private static final long serialVersionUID = -6971431362627219416L; - private final Map internalMap = new HashMap<>(); + private transient Map internalMap = new HashMap(); @Override public void clear() { @@ -30,10 +30,10 @@ public class JedisByteHashMap implements Map, Cloneable, Seriali } @Override - public Set> entrySet() { - Iterator> iterator = internalMap.entrySet() + public Set> entrySet() { + Iterator> iterator = internalMap.entrySet() .iterator(); - HashSet> hashSet = new HashSet<>(); + HashSet> hashSet = new HashSet>(); while (iterator.hasNext()) { Entry entry = iterator.next(); hashSet.add(new JedisByteEntry(entry.getKey().data, entry.getValue())); @@ -54,7 +54,7 @@ public class JedisByteHashMap implements Map, Cloneable, Seriali @Override public Set keySet() { - Set keySet = new HashSet<>(); + Set keySet = new HashSet(); Iterator iterator = internalMap.keySet().iterator(); while (iterator.hasNext()) { keySet.add(iterator.next().data); @@ -94,7 +94,7 @@ public class JedisByteHashMap implements Map, Cloneable, Seriali return internalMap.values(); } - private static final class ByteArrayWrapper implements Serializable { + private static final class ByteArrayWrapper { private final byte[] data; public ByteArrayWrapper(byte[] data) { @@ -106,10 +106,9 @@ public class JedisByteHashMap implements Map, Cloneable, Seriali @Override public boolean equals(Object other) { - if (other == null) return false; - if (other == this) return true; - if (!(other instanceof ByteArrayWrapper)) return false; - + if (!(other instanceof ByteArrayWrapper)) { + return false; + } return Arrays.equals(data, ((ByteArrayWrapper) other).data); } @@ -145,4 +144,4 @@ public class JedisByteHashMap implements Map, Cloneable, Seriali } } -} +} \ No newline at end of file diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/JedisClusterCRC16.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/JedisClusterCRC16.java index 602f70d86..98b478744 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/JedisClusterCRC16.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/JedisClusterCRC16.java @@ -1,57 +1,48 @@ package com.fr.third.redis.clients.jedis.util; -import com.fr.third.redis.clients.jedis.exceptions.JedisClusterOperationException; - /** * CRC16 Implementation according to CCITT standard Polynomial : 1021 (x^16 + x^12 + x^5 + 1) See Appendix A. CRC16 reference implementation in ANSI * C */ public final class JedisClusterCRC16 { - private static final int[] LOOKUP_TABLE = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, - 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, - 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A, - 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, - 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, - 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, - 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, - 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, - 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, - 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, - 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, - 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, - 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, - 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, - 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, - 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, - 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, - 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, - 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, - 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, - 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, - 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0, }; + private static final int[] LOOKUP_TABLE = {0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, + 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, + 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A, + 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, + 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, + 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, + 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, + 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, + 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, + 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, + 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, + 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, + 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, + 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, + 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, + 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, + 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, + 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, + 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, + 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, + 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, + 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0,}; - private JedisClusterCRC16() { - throw new InstantiationError("Must not instantiate this class"); + private JedisClusterCRC16(){ + throw new InstantiationError( "Must not instantiate this class" ); } public static int getSlot(String key) { - if (key == null) { - throw new JedisClusterOperationException("Slot calculation of null is impossible"); - } - key = JedisClusterHashTagUtil.getHashTag(key); - // optimization with modulo operator with power of 2 equivalent to getCRC16(key) % 16384 + // optimization with modulo operator with power of 2 + // equivalent to getCRC16(key) % 16384 return getCRC16(key) & (16384 - 1); } public static int getSlot(byte[] key) { - if (key == null) { - throw new JedisClusterOperationException("Slot calculation of null is impossible"); - } - int s = -1; int e = -1; boolean sFound = false; @@ -75,8 +66,6 @@ public final class JedisClusterCRC16 { * Create a CRC16 checksum from the bytes. implementation is from mp911de/lettuce, modified with * some more optimizations * @param bytes - * @param s - * @param e * @return CRC16 as integer value See Issue 733 */ diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/JedisURIHelper.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/JedisURIHelper.java index 95d667ade..6f06ae2a7 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/JedisURIHelper.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/JedisURIHelper.java @@ -9,20 +9,8 @@ public final class JedisURIHelper { private static final String REDIS = "redis"; private static final String REDISS = "rediss"; - private JedisURIHelper() { - throw new InstantiationError("Must not instantiate this class"); - } - - public static String getUser(URI uri) { - String userInfo = uri.getUserInfo(); - if (userInfo != null) { - String user = userInfo.split(":", 2)[0]; - if (user.isEmpty()) { - user = null; // return null user is not specified - } - return user; - } - return null; + private JedisURIHelper(){ + throw new InstantiationError( "Must not instantiate this class" ); } public static String getPassword(URI uri) { diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/KeyMergeUtil.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/KeyMergeUtil.java index 3ce0faa1c..0b05f9136 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/KeyMergeUtil.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/KeyMergeUtil.java @@ -1,8 +1,8 @@ package com.fr.third.redis.clients.jedis.util; public final class KeyMergeUtil { - private KeyMergeUtil() { - throw new InstantiationError("Must not instantiate this class"); + private KeyMergeUtil(){ + throw new InstantiationError( "Must not instantiate this class" ); } public static String[] merge(String destKey, String[] keys) { diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Pool.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Pool.java index 710a7cb17..dd261c1ed 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Pool.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Pool.java @@ -12,23 +12,15 @@ import com.fr.third.redis.clients.jedis.exceptions.JedisException; import com.fr.third.redis.clients.jedis.exceptions.JedisExhaustedPoolException; public abstract class Pool implements Closeable { - - /** - * @deprecated This will be private in future. - */ - @Deprecated protected GenericObjectPool internalPool; /** * Using this constructor means you have to set and initialize the internalPool yourself. - * - * @deprecated This constructor will be removed in future. */ - @Deprecated public Pool() { } - public Pool(final GenericObjectPoolConfig poolConfig, PooledObjectFactory factory) { + public Pool(final GenericObjectPoolConfig poolConfig, PooledObjectFactory factory) { initPool(poolConfig, factory); } @@ -41,13 +33,7 @@ public abstract class Pool implements Closeable { return this.internalPool.isClosed(); } - /** - * @param poolConfig - * @param factory - * @deprecated This method will be private in future. - */ - @Deprecated - public void initPool(final GenericObjectPoolConfig poolConfig, PooledObjectFactory factory) { + public void initPool(final GenericObjectPoolConfig poolConfig, PooledObjectFactory factory) { if (this.internalPool != null) { try { @@ -56,18 +42,7 @@ public abstract class Pool implements Closeable { } } - this.internalPool = new GenericObjectPool<>(factory, poolConfig); - } - - /** - * This call only clears idle instances, not borrowed instances. - */ - protected void clearInternalPool() { - try { - this.internalPool.clear(); - } catch (Exception e) { - throw new JedisException("Could not clear the pool", e); - } + this.internalPool = new GenericObjectPool(factory, poolConfig); } public T getResource() { @@ -86,6 +61,9 @@ public abstract class Pool implements Closeable { } protected void returnResourceObject(final T resource) { + if (resource == null) { + return; + } try { internalPool.returnObject(resource); } catch (Exception e) { @@ -93,13 +71,13 @@ public abstract class Pool implements Closeable { } } - public void returnBrokenResource(final T resource) { + protected void returnBrokenResource(final T resource) { if (resource != null) { returnBrokenResourceObject(resource); } } - public void returnResource(final T resource) { + protected void returnResource(final T resource) { if (resource != null) { returnResourceObject(resource); } @@ -113,7 +91,7 @@ public abstract class Pool implements Closeable { try { internalPool.invalidateObject(resource); } catch (Exception e) { - throw new JedisException("Could not return the broken resource to the pool", e); + throw new JedisException("Could not return the resource to the pool", e); } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/RedisInputStream.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/RedisInputStream.java index 30d7c3e41..aacef83c7 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/RedisInputStream.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/RedisInputStream.java @@ -9,10 +9,7 @@ package com.fr.third.redis.clients.jedis.util; -import java.io.ByteArrayOutputStream; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import com.fr.third.redis.clients.jedis.exceptions.JedisConnectionException; diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/RedisOutputStream.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/RedisOutputStream.java index 11e9682a2..626d7b0d3 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/RedisOutputStream.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/RedisOutputStream.java @@ -15,25 +15,25 @@ public final class RedisOutputStream extends FilterOutputStream { protected int count; private final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, - 999999999, Integer.MAX_VALUE }; + 999999999, Integer.MAX_VALUE }; private final static byte[] DigitTens = { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', - '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', '2', - '2', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4', '4', - '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', '6', '6', '6', '6', '6', - '6', '6', '6', '6', '6', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8', - '8', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', }; + '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', '2', + '2', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4', '4', + '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', '6', '6', '6', '6', '6', + '6', '6', '6', '6', '6', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8', + '8', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', }; private final static byte[] DigitOnes = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', - '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', - '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', - '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', - '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', - '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', }; + '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', + '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', + '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', + '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', + '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', }; private final static byte[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', - 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', - 't', 'u', 'v', 'w', 'x', 'y', 'z' }; + 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', + 't', 'u', 'v', 'w', 'x', 'y', 'z' }; public RedisOutputStream(final OutputStream out) { this(out, 8192); diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/SafeEncoder.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/SafeEncoder.java index be91008c8..75ac40e56 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/SafeEncoder.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/SafeEncoder.java @@ -1,8 +1,6 @@ package com.fr.third.redis.clients.jedis.util; import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; import com.fr.third.redis.clients.jedis.Protocol; import com.fr.third.redis.clients.jedis.exceptions.JedisDataException; @@ -12,9 +10,8 @@ import com.fr.third.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 { - - private SafeEncoder() { - throw new InstantiationError("Must not instantiate this class"); + private SafeEncoder(){ + throw new InstantiationError( "Must not instantiate this class" ); } public static byte[][] encodeMany(final String... strs) { @@ -43,28 +40,4 @@ public final class SafeEncoder { throw new JedisException(e); } } - - /** - * This method takes an object and will convert all bytes[] and list of byte[] and will encode the - * object in a recursive way. - * @param dataToEncode - * @return the object fully encoded - */ - public static Object encodeObject(Object dataToEncode) { - if (dataToEncode instanceof byte[]) { - return SafeEncoder.encode((byte[]) dataToEncode); - } - - if (dataToEncode instanceof List) { - List arrayToDecode = (List) dataToEncode; - List returnValueArray = new ArrayList(arrayToDecode.size()); - for (Object arrayEntry : arrayToDecode) { - // recursive call and add to list - returnValueArray.add(encodeObject(arrayEntry)); - } - return returnValueArray; - } - - return dataToEncode; - } } diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Sharded.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Sharded.java index ee6f516d9..9f35bfb2c 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Sharded.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Sharded.java @@ -15,7 +15,7 @@ public class Sharded> { public static final int DEFAULT_WEIGHT = 1; private TreeMap nodes; private final Hashing algo; - private final Map, R> resources = new LinkedHashMap<>(); + private final Map, R> resources = new LinkedHashMap, R>(); /** * The default pattern used for extracting a key tag. The pattern must have a group (between @@ -49,15 +49,14 @@ public class Sharded> { } private void initialize(List shards) { - nodes = new TreeMap<>(); + 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++) { + if (shardInfo.getName() == null) for (int n = 0; n < 160 * shardInfo.getWeight(); n++) { nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n), shardInfo); } - else for (int n = 0; n < N; n++) { + else for (int n = 0; n < 160 * shardInfo.getWeight(); n++) { nodes.put(this.algo.hash(shardInfo.getName() + "*" + n), shardInfo); } resources.put(shardInfo, shardInfo.createResource()); diff --git a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Slowlog.java b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Slowlog.java index e686e066f..a49ef16a7 100644 --- a/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Slowlog.java +++ b/fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/util/Slowlog.java @@ -3,17 +3,11 @@ package com.fr.third.redis.clients.jedis.util; import java.util.ArrayList; import java.util.List; -import com.fr.third.redis.clients.jedis.HostAndPort; - public class Slowlog { - private final long id; private final long timeStamp; private final long executionTime; private final List args; - private HostAndPort clientIpPort; - private String clientName; - private static final String COMMA = ","; @SuppressWarnings("unchecked") @@ -24,20 +18,16 @@ public class Slowlog { this.executionTime = (Long) properties.get(2); List bargs = (List) properties.get(3); - this.args = new ArrayList<>(bargs.size()); + this.args = new ArrayList(bargs.size()); for (byte[] barg : bargs) { this.args.add(SafeEncoder.encode(barg)); } - if (properties.size() == 4) return; - - this.clientIpPort = HostAndPort.from(SafeEncoder.encode((byte[]) properties.get(4))); - this.clientName = SafeEncoder.encode((byte[]) properties.get(5)); } @SuppressWarnings("unchecked") public static List from(List nestedMultiBulkReply) { - List logs = new ArrayList<>(nestedMultiBulkReply.size()); + List logs = new ArrayList(nestedMultiBulkReply.size()); for (Object obj : nestedMultiBulkReply) { List properties = (List) obj; logs.add(new Slowlog(properties)); @@ -45,7 +35,7 @@ public class Slowlog { return logs; } - + public long getId() { return id; } @@ -62,14 +52,6 @@ public class Slowlog { return args; } - public HostAndPort getClientIpPort() { - return clientIpPort; - } - - public String getClientName() { - return clientName; - } - @Override public String toString() { return new StringBuilder().append(id).append(COMMA).append(timeStamp).append(COMMA)