Browse Source

Revert "REPORT-73902 update: jedis升级"

This reverts commit d01a8a04e3.
bugfix/10.0
lidongy 2 years ago
parent
commit
6885b82005
  1. 3
      fine-jedis/README.md
  2. 14
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/BaseKeyedPooledObjectFactory.java
  3. 10
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/BaseObjectPool.java
  4. 2
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/BasePooledObjectFactory.java
  5. 30
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/DestroyMode.java
  6. 273
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/KeyedObjectPool.java
  7. 43
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/KeyedPooledObjectFactory.java
  8. 166
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/ObjectPool.java
  9. 188
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PoolUtils.java
  10. 61
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PooledObject.java
  11. 45
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PooledObjectFactory.java
  12. 1
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/PooledObjectState.java
  13. 16
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/AbandonedConfig.java
  14. 397
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/BaseGenericObjectPool.java
  15. 46
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/BaseObjectPoolConfig.java
  16. 14
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/CallStackUtils.java
  17. 2
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultEvictionPolicy.java
  18. 23
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultPooledObject.java
  19. 6
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultPooledObjectInfo.java
  20. 10
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/DefaultPooledObjectInfoMBean.java
  21. 1
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionConfig.java
  22. 7
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionPolicy.java
  23. 175
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionTimer.java
  24. 277
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericKeyedObjectPool.java
  25. 9
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericKeyedObjectPoolConfig.java
  26. 35
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericKeyedObjectPoolMXBean.java
  27. 260
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericObjectPool.java
  28. 9
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericObjectPoolConfig.java
  29. 40
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/GenericObjectPoolMXBean.java
  30. 1
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/InterruptibleReentrantLock.java
  31. 63
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/LinkedBlockingDeque.java
  32. 8
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/NoOpCallStack.java
  33. 122
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/PoolImplUtils.java
  34. 9
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/SecurityManagerCallStack.java
  35. 63
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/SoftReferenceObjectPool.java
  36. 1
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/package.html
  37. 2
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/CglibProxySource.java
  38. 2
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/JdkProxySource.java
  39. 6
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/ProxiedKeyedObjectPool.java
  40. 2
      fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/package.html
  41. 100
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/AccessControlLogEntry.java
  42. 53
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/AccessControlUser.java
  43. 1113
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryClient.java
  44. 1715
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedis.java
  45. 1333
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedisCluster.java
  46. 31
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedisPubSub.java
  47. 477
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryShardedJedis.java
  48. 2
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BitPosParams.java
  49. 794
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BuilderFactory.java
  50. 624
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Client.java
  51. 174
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Connection.java
  52. 4
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/DebugParams.java
  53. 210
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/DefaultJedisClientConfig.java
  54. 228
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/DefaultJedisSocketFactory.java
  55. 3
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/GeoCoordinate.java
  56. 9
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/GeoRadiusResponse.java
  57. 57
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/HostAndPort.java
  58. 6
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/HostAndPortMapper.java
  59. 1488
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Jedis.java
  60. 76
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClientConfig.java
  61. 4935
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisCluster.java
  62. 201
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterCommand.java
  63. 124
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterConnectionHandler.java
  64. 15
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterHostAndPortMap.java
  65. 194
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterInfoCache.java
  66. 209
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisFactory.java
  67. 269
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPool.java
  68. 24
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPoolAbstract.java
  69. 2
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPoolConfig.java
  70. 328
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisPubSub.java
  71. 270
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisSentinelPool.java
  72. 32
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisShardInfo.java
  73. 87
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisSlotBasedConnectionHandler.java
  74. 55
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisSocketFactory.java
  75. 10
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Module.java
  76. 369
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/MultiKeyPipelineBase.java
  77. 8
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Pipeline.java
  78. 866
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/PipelineBase.java
  79. 120
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Protocol.java
  80. 4
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Queable.java
  81. 14
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ScanParams.java
  82. 1
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ScanResult.java
  83. 453
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ShardedJedis.java
  84. 17
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ShardedJedisPipeline.java
  85. 51
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ShardedJedisPool.java
  86. 20
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/SortingParams.java
  87. 52
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamConsumersInfo.java
  88. 41
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamEntry.java
  89. 120
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamEntryID.java
  90. 60
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamGroupInfo.java
  91. 82
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamInfo.java
  92. 59
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamPendingEntry.java
  93. 38
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamPendingSummary.java
  94. 32
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Transaction.java
  95. 14
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Tuple.java
  96. 15
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ZParams.java
  97. 30
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/FlushMode.java
  98. 21
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/ListDirection.java
  99. 6
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/Rawable.java
  100. 21
      fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/UnblockType.java
  101. Some files were not shown because too many files have changed in this diff Show More

3
fine-jedis/README.md

@ -1,3 +0,0 @@
# fine-jedis
版本为3.6.0,内置的apache-commons-pool版本为2.9.0

14
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 <code>KeyedPooledObjectFactory</code>.
* <p>
* All operations defined here are essentially no-op's.
* </p>
* <p>
* This class is immutable, and therefore thread-safe.
* </p>
*
* @see KeyedPooledObjectFactory
*
@ -32,8 +30,8 @@ package com.fr.third.org.apache.commons.pool2;
*
* @since 2.0
*/
public abstract class BaseKeyedPooledObjectFactory<K, V> extends BaseObject
implements KeyedPooledObjectFactory<K, V> {
public abstract class BaseKeyedPooledObjectFactory<K,V> extends BaseObject
implements KeyedPooledObjectFactory<K,V> {
/**
* Create an instance that can be served by the pool.
@ -66,7 +64,6 @@ public abstract class BaseKeyedPooledObjectFactory<K, V> extends BaseObject
* Destroy an instance no longer needed by the pool.
* <p>
* The default implementation is a no-op.
* </p>
*
* @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<K, V> extends BaseObject
* Ensures that the instance is safe to be returned by the pool.
* <p>
* The default implementation always returns {@code true}.
* </p>
*
* @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 <code>true</code> in the default implementation
*/
@Override
public boolean validateObject(final K key, final PooledObject<V> p) {
@ -96,7 +92,6 @@ public abstract class BaseKeyedPooledObjectFactory<K, V> extends BaseObject
* Reinitialize an instance to be returned by the pool.
* <p>
* The default implementation is a no-op.
* </p>
*
* @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<K, V> extends BaseObject
* Uninitialize an instance to be returned to the idle object pool.
* <p>
* The default implementation is a no-op.
* </p>
*
* @param key the key used when selecting the object
* @param p a {@code PooledObject} wrapping the instance to be passivated

10
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}.
* <p>
* This class is intended to be thread-safe.
* </p>
*
* @param <T> Type of element pooled in this pool.
*
@ -85,9 +84,8 @@ public abstract class BaseObjectPool<T> extends BaseObject implements ObjectPool
/**
* {@inheritDoc}
* <p>
* This affects the behavior of {@code isClosed} and
* {@code assertOpen}.
* </p>
* This affects the behavior of <code>isClosed</code> and
* <code>assertOpen</code>.
*/
@Override
public void close() {
@ -97,14 +95,14 @@ public abstract class BaseObjectPool<T> extends BaseObject implements ObjectPool
/**
* Has this pool instance been closed.
*
* @return {@code true} when this pool has been closed.
* @return <code>true</code> when this pool has been closed.
*/
public final boolean isClosed() {
return closed;
}
/**
* Throws an {@code IllegalStateException} when this pool has been
* Throws an <code>IllegalStateException</code> when this pool has been
* closed.
*
* @throws IllegalStateException when this pool has been closed.

2
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 <code>PoolableObjectFactory</code>.
* <p>
* All operations defined here are essentially no-op's.
* <p>

30
fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/DestroyMode.java

@ -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
}

273
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.
* <p>
* A keyed pool maintains a pool of instances for each key value.
* </p>
* <p>
* Example of use:
* </p>
* <pre style="border:solid thin; padding: 1ex;"
* > Object obj = <code style="color:#00C">null</code>;
* Object key = <code style="color:#C00">"Key"</code>;
@ -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}).
* </p>
* <p>
* See {@link com.fr.third.org.apache.commons.pool2.impl.GenericKeyedObjectPool
* See {@link org.apache.commons.pool2.impl.GenericKeyedObjectPool
* GenericKeyedObjectPool} for an implementation.
* </p>
*
* @param <K> The type of keys maintained by this pool.
* @param <V> 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<K, V> 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<K> keys, final int count) throws Exception, IllegalArgumentException {
if (keys == null) {
throw new IllegalArgumentException(PoolUtils.MSG_NULL_KEYS);
}
final Iterator<K> iter = keys.iterator();
while (iter.hasNext()) {
addObjects(iter.next(), count);
}
}
public interface KeyedObjectPool<K,V> 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 <code>key</code>.
* <p>
* 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<K, V> extends Closeable {
* {@link KeyedPooledObjectFactory#activateObject activateObject} and then
* (optionally) validated with
* {@link KeyedPooledObjectFactory#validateObject validateObject}.
* </p>
* <p>
* By contract, clients <strong>must</strong> 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 <code>key</code>
* that is {@link Object#equals equivalent} to the one used to borrow the
* instance in the first place.
* </p>
* <p>
* 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).
* </p>
*
* @param key the key used to obtain the object
*
@ -176,146 +98,133 @@ public interface KeyedObjectPool<K, V> 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, <code>obj</code>
* <strong>must</strong> have been obtained using
* {@link #borrowObject borrowObject} or a related method as defined in an
* implementation or sub-interface using a <code>key</code> 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.
* <p>
* By contract, <code>obj</code> <strong>must</strong> have been obtained
* using {@link #borrowObject borrowObject} or a related method as defined
* in an implementation or sub-interface using a <code>key</code> that is
* equivalent to the one used to borrow the <code>Object</code> in the first
* place.
* <p>
* 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.
* <p>
* Calling {@link #addObject addObject} or
* {@link #borrowObject borrowObject} after invoking this method on a pool
* will cause them to throw an {@link IllegalStateException}.
* </p>
* <p>
* Implementations should silently fail if not all resources can be freed.
* </p>
* 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</code> 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
* <code>key</code> 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</code> 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 <code>key</code>.
* 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 <code>key</code>.
= */
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.
* <p>
* By contract, {@code obj} <strong>must</strong> 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.
* </p>
* <p>
* This method should be used when an object that has been borrowed is
* determined (due to an exception or other problem) to be invalid.
* </p>
* 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}.
* <p>
* By contract, {@code obj} <strong>must</strong> 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.
* </p>
* <p>
* This method should be used when an object that has been borrowed is
* determined (due to an exception or other problem) to be invalid.
* </p>
* Clears the specified pool, removing all pooled instances corresponding to
* the given <code>key</code> (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}
* <strong>must</strong> 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.
* <p>
* Calling {@link #addObject addObject} or
* {@link #borrowObject borrowObject} after invoking this method on a pool
* will cause them to throw an {@link IllegalStateException}.
* <p>
* Implementations should silently fail if not all resources can be freed.
*/
void returnObject(K key, V obj) throws Exception;
@Override
void close();
}

43
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;
* <p>
* By contract, when an {@link KeyedObjectPool}
* delegates to a {@link KeyedPooledObjectFactory},
* </p>
* <ol>
* <li>
* {@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
* <code>validateObject</code> 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;
* <li>
* {@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 <code>validateObject</code>,
* 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.
* <code>KeyedPoolableObjectFactory</code> at a time.
* <p>
* 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&lt;V&gt;}. These are the object wrappers that
* pools use to track and maintain state informations about the objects that
* they manage.
* </p>
*
* @see KeyedObjectPool
* @see BaseKeyedPooledObjectFactory
@ -74,8 +72,7 @@ package com.fr.third.org.apache.commons.pool2;
*
* @since 2.0
*/
public interface KeyedPooledObjectFactory<K, V> {
public interface KeyedPooledObjectFactory<K,V> {
/**
* 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<K, V> {
* Destroy an instance no longer needed by the pool.
* <p>
* 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 <code>obj</code> will be in and the
* implementation should be prepared to handle unexpected errors.
* </p>
* <p>
* Also, an implementation must take in to consideration that instances lost
* to the garbage collector may never be destroyed.
* </p>
*
* @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<K, V> {
*/
void destroyObject(K key, PooledObject<V> 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<V> 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 <code>false</code> if <code>obj</code> is not valid and should
* be dropped from the pool, <code>true</code> otherwise.
*/
boolean validateObject(K key, PooledObject<V> p);
@ -150,7 +125,7 @@ public interface KeyedPooledObjectFactory<K, V> {
* @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 <code>obj</code>,
* this exception may be swallowed by the pool.
*
* @see #destroyObject
@ -163,7 +138,7 @@ public interface KeyedPooledObjectFactory<K, V> {
* @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 <code>obj</code>,
* this exception may be swallowed by the pool.
*
* @see #destroyObject

166
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.
* <p>
* Example of use:
* </p>
* <pre style="border:solid thin; padding: 1ex;"
* > Object obj = <code style="color:#00C">null</code>;
*
@ -47,7 +46,6 @@ import java.util.NoSuchElementException;
* }</pre>
* <p>
* See {@link BaseObjectPool} for a simple base implementation.
* </p>
*
* @param <T> Type of element pooled in this pool.
*
@ -58,39 +56,6 @@ import java.util.NoSuchElementException;
* @since 2.0
*/
public interface ObjectPool<T> 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.
* <p>
@ -99,17 +64,14 @@ public interface ObjectPool<T> extends Closeable {
* idle object and have been activated with
* {@link PooledObjectFactory#activateObject} and then validated with
* {@link PooledObjectFactory#validateObject}.
* </p>
* <p>
* By contract, clients <strong>must</strong> return the borrowed instance
* using {@link #returnObject}, {@link #invalidateObject}, or a related
* method as defined in an implementation or sub-interface.
* </p>
* <p>
* 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).
* </p>
*
* @return an instance from this pool.
*
@ -126,39 +88,57 @@ public interface ObjectPool<T> 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, <code>obj</code>
* <strong>must</strong> 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.
* <p>
* Calling {@link #addObject} or {@link #borrowObject} after invoking this
* method on a pool will cause them to throw an {@link IllegalStateException}.
* </p>
* By contract, <code>obj</code> <strong>must</strong> have been obtained
* using {@link #borrowObject} or a related method as defined in an
* implementation or sub-interface.
* <p>
* Implementations should silently fail if not all resources can be freed.
* </p>
* 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. <code>addObject</code> 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<T> extends Closeable {
int getNumIdle();
/**
* Invalidates an object from the pool.
* <p>
* By contract, {@code obj} <strong>must</strong> have been obtained
* using {@link #borrowObject} or a related method as defined in an
* implementation or sub-interface.
* </p>
* <p>
* This method should be used when an object that has been borrowed is
* determined (due to an exception or other problem) to be invalid.
* </p>
*
* @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}
* <p>
* By contract, {@code obj} <strong>must</strong> have been obtained
* using {@link #borrowObject} or a related method as defined in an
* implementation or sub-interface.
* </p>
* <p>
* This method should be used when an object that has been borrowed is
* determined (due to an exception or other problem) to be invalid.
* </p>
* 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}
* <strong>must</strong> 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.
* <p>
* Calling {@link #addObject} or {@link #borrowObject} after invoking this
* method on a pool will cause them to throw an {@link IllegalStateException}.
* <p>
* Implementations should silently fail if not all resources can be freed.
*/
void returnObject(T obj) throws Exception;
@Override
void close();
}

188
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 <code>pool</code> is <code>null</code> or when
* <code>minIdle</code> is negative or when <code>period</code>
* isn't valid for {@link Timer#schedule(TimerTask, long, long)}
*/
public static <T> TimerTask checkMinIdle(final ObjectPool<T> 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<T>(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 <code>keyedPool</code>, <code>key</code> is
* <code>null</code> or when <code>minIdle</code> is negative or
* when <code>period</code> isn't valid for
* {@link Timer#schedule(TimerTask, long, long)}.
*/
public static <K, V> TimerTask checkMinIdle(
final KeyedObjectPool<K, V> 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<K, V>(
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.
* <code>Collection</code> <code>keys</code> 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 <code>keyedPool</code>, <code>keys</code>, or any of the
* values in the collection is <code>null</code> or when
* <code>minIdle</code> is negative or when <code>period</code>
* isn't valid for {@link Timer#schedule(TimerTask, long, long)}
* .
* @see #checkMinIdle(KeyedObjectPool, Object, int, long)
*/
public static <K, V> Map<K, TimerTask> 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<K, TimerTask> tasks = new HashMap<>(keys.size());
final Map<K, TimerTask> tasks = new HashMap<K, TimerTask>(keys.size());
final Iterator<K> 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 <code>addObject()</code> on <code>pool</code> <code>count</code>
* 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 <code>pool</code> is <code>null</code>.
*/
@Deprecated
public static <T> void prefill(final ObjectPool<T> 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 <code>addObject(Object)</code> on <code>keyedPool</code> with
* <code>key</code> <code>count</code> 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 <code>key</code>.
* @param <K> the type of the pool key
* @param <V> 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 <code>keyedPool</code> or <code>key</code> is
* <code>null</code>.
*/
@Deprecated
public static <K, V> void prefill(final KeyedObjectPool<K, V> 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 <code>addObject(Object)</code> on <code>keyedPool</code> with each
* key in <code>keys</code> for <code>count</code> 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 <code>keys</code> 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 <code>key</code>.
* @param <K> the type of the pool key
* @param <V> 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 <code>keyedPool</code>, <code>keys</code>, or any value
* in <code>keys</code> is <code>null</code>.
* @see #prefill(KeyedObjectPool, Object, int)
* @deprecated Use {@link KeyedObjectPool#addObjects(Collection, int)}.
*/
@Deprecated
public static <K, V> void prefill(final KeyedObjectPool<K, V> keyedPool,
final Collection<K> 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<K> 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 <T> 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 <T> ObjectPool<T> synchronizedPool(final ObjectPool<T> 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<T>(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<K, V>(keyedPool);
}
/**
@ -371,7 +369,7 @@ public final class PoolUtils {
*/
public static <T> PooledObjectFactory<T> synchronizedPooledFactory(
final PooledObjectFactory<T> factory) {
return new SynchronizedPooledObjectFactory<>(factory);
return new SynchronizedPooledObjectFactory<T>(factory);
}
/**
@ -387,7 +385,7 @@ public final class PoolUtils {
*/
public static <K, V> KeyedPooledObjectFactory<K, V> synchronizedKeyedPooledFactory(
final KeyedPooledObjectFactory<K, V> keyedFactory) {
return new SynchronizedKeyedPooledObjectFactory<>(keyedFactory);
return new SynchronizedKeyedPooledObjectFactory<K, V>(keyedFactory);
}
/**
@ -401,8 +399,6 @@ public final class PoolUtils {
* the ObjectPool to be decorated so it shrinks its idle count
* when possible.
* @param <T> 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 &lt; factor then the pool
* shrinks less aggressively.
* @param <T> 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 <T> ObjectPool<T> erodingPool(final ObjectPool<T> 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<T>(pool, factor);
}
/**
@ -463,8 +456,6 @@ public final class PoolUtils {
* count when possible.
* @param <K> the type of the pool key
* @param <V> 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 <K> the type of the pool key
* @param <V> 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 <K> the type of the pool key
* @param <V> 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<K, V> 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<K, V>(keyedPool, factor);
}
return new ErodingKeyedObjectPool<>(keyedPool, factor);
return new ErodingKeyedObjectPool<K, V>(keyedPool, factor);
}
/**
* Gets the {@code Timer} for checking keyedPool's idle count.
* Get the <code>Timer</code> 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<T> 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<K, V> 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<K, V> 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<T> 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<T> 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<K, V> 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<T> implements
PooledObjectFactory<T> {
/** Synchronization lock */
private final WriteLock writeLock = new ReentrantReadWriteLock().writeLock();
@ -1142,7 +1125,7 @@ public final class PoolUtils {
private final PooledObjectFactory<T> 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<K, V>
implements KeyedPooledObjectFactory<K, V> {
/** Synchronization lock */
private final WriteLock writeLock = new ReentrantReadWriteLock().writeLock();
@ -1259,7 +1241,7 @@ public final class PoolUtils {
private final KeyedPooledObjectFactory<K, V> 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 <T> type of objects in the pool
*/
private static class ErodingObjectPool<T> implements ObjectPool<T> {
/** Underlying object pool */
private final ObjectPool<T> 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<K, V> implements
KeyedObjectPool<K, V> {
/** Underlying pool */
private final KeyedObjectPool<K, V> 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<K, V> 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<K, V> extends
ErodingKeyedObjectPool<K, V> {
/** Erosion factor - same for all pools */
private final float factor;
@ -1804,7 +1783,7 @@ public final class PoolUtils {
private final Map<K, ErodingFactor> factors = Collections.synchronizedMap(new HashMap<K, ErodingFactor>());
/**
* 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() + '}';
}
}
}
}

61
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.
* <p>
* Implementations of this class are required to be thread-safe.
* </p>
*
* @param <T> the type of object in the pool
*
@ -33,7 +32,7 @@ import java.util.Deque;
public interface PooledObject<T> extends Comparable<PooledObject<T>> {
/**
* 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<T> extends Comparable<PooledObject<T>> {
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<T> extends Comparable<PooledObject<T>> {
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<T> extends Comparable<PooledObject<T>> {
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<T> extends Comparable<PooledObject<T>> {
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<T> extends Comparable<PooledObject<T>> {
*<p>
* Note: This class has a natural ordering that is inconsistent with
* equals if distinct objects have the same identity hash code.
* </p>
* <p>
* {@inheritDoc}
* </p>
*/
@Override
int compareTo(PooledObject<T> other);
@ -131,12 +118,12 @@ public interface PooledObject<T> extends Comparable<PooledObject<T>> {
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 <code>true</code> if the object was placed in the
* {@link PooledObjectState#EVICTION} state otherwise
* {@code false}
* <code>false</code>
*/
boolean startEvictionTest();
@ -180,17 +167,17 @@ public interface PooledObject<T> extends Comparable<PooledObject<T>> {
*/
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<T> extends Comparable<PooledObject<T>> {
*/
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();
}

45
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;
* <p>
* By contract, when an {@link ObjectPool} delegates to a
* {@link PooledObjectFactory},
* </p>
* <ol>
* <li>
* {@link #makeObject} is called whenever a new instance is needed.
@ -54,7 +53,7 @@ package com.fr.third.org.apache.commons.pool2;
* </ol>
* {@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 <code>PoolableObjectFactory</code>
* at a time.
* <p>
* 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&lt;V&gt;}. These are the object wrappers that
* pools use to track and maintain state information about the objects that
* they manage.
* </p>
*
* @param <T> 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<T> {
/**
* 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<T> {
PooledObject<T> 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.
* <p>
* 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 <code>obj</code> will be in and the
* implementation should be prepared to handle unexpected errors.
* </p>
* <p>
* 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<T> {
*/
void destroyObject(PooledObject<T> 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<T> 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 <code>false</code> if <code>obj</code> is not valid and should
* be dropped from the pool, <code>true</code> otherwise.
*/
boolean validateObject(PooledObject<T> 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 <code>obj</code>,
* this exception may be swallowed by the pool.
*
* @see #destroyObject
@ -149,11 +124,11 @@ public interface PooledObjectFactory<T> {
void activateObject(PooledObject<T> 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 <code>obj</code>,
* this exception may be swallowed by the pool.
*
* @see #destroyObject

1
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.
*/

16
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 {
*
* <p>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() &gt; getMaxTotal() - 3}</p>
* <code>getNumActive() &gt; getMaxTotal() - 3</code></p>
*
* @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 <code>true</code> 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 <code>true</code> will enable
* the recording of a stack trace on every use
* of a pooled object
*/

397
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<T> 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<T> 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<T> extends BaseObject {
* overridden by the config
* @param jmxNamePrefix Prefix to be used for JMX name for the new pool
*/
public BaseGenericObjectPool(final BaseObjectPoolConfig<T> 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<T> extends BaseObject {
if (cl == null) {
factoryClassLoader = null;
} else {
factoryClassLoader = new WeakReference<>(cl);
factoryClassLoader = new WeakReference<ClassLoader>(cl);
}
fairness = config.getFairness();
@ -189,11 +185,11 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
}
/**
* Returns whether to block when the {@code borrowObject()} method is
* Returns whether to block when the <code>borrowObject()</code> 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 <code>true</code> if <code>borrowObject()</code> should block
* when the pool is exhausted
*
* @see #setBlockWhenExhausted
@ -203,12 +199,12 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
}
/**
* Sets whether to block when the {@code borrowObject()} method is
* Sets whether to block when the <code>borrowObject()</code> 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 <code>true</code> if
* <code>borrowObject()</code> should block
* when the pool is exhausted
*
* @see #getBlockWhenExhausted
@ -217,42 +213,14 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
this.blockWhenExhausted = blockWhenExhausted;
}
/**
* Initializes the receiver with the given configuration.
*
* @param config Initialization source.
*/
protected void setConfig(final BaseObjectPoolConfig<T> 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<T> 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
* <code>borrowObject()</code> 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.
* <code>borrowObject()</code> method may block indefinitely.
*
* @return the maximum number of milliseconds {@code borrowObject()}
* @return the maximum number of milliseconds <code>borrowObject()</code>
* will block.
*
* @see #setMaxWaitMillis
@ -264,13 +232,13 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
/**
* Sets the maximum amount of time (in milliseconds) the
* {@code borrowObject()} method should block before throwing an
* <code>borrowObject()</code> 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.
* <code>borrowObject()</code> method may block indefinitely.
*
* @param maxWaitMillis the maximum number of milliseconds
* {@code borrowObject()} will block or negative
* <code>borrowObject()</code> will block or negative
* for indefinitely.
*
* @see #getMaxWaitMillis
@ -281,14 +249,14 @@ public abstract class BaseGenericObjectPool<T> 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 <code>true</code> if the pool is configured with LIFO behaviour
* or <code>false</code> if the pool is configured with FIFO
* behaviour
*
* @see #setLifo
*/
@ -300,7 +268,7 @@ public abstract class BaseGenericObjectPool<T> 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 <code>true</code> 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<T> 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 <code>true</code> if the pool is to be configured with LIFO
* behaviour or <code>false</code> if the pool is to be
* configured with FIFO behaviour
*
* @see #getLifo()
*/
@ -325,13 +293,13 @@ public abstract class BaseGenericObjectPool<T> 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 <code>borrowObject()</code> method. Validation is
* performed by the <code>validateObject()</code> method of the factory
* associated with the pool. If the object fails to validate, then
* {@code borrowObject()} will fail.
* <code>borrowObject()</code> will fail.
*
* @return {@code true} if newly created objects are validated before
* being returned from the {@code borrowObject()} method
* @return <code>true</code> if newly created objects are validated before
* being returned from the <code>borrowObject()</code> method
*
* @see #setTestOnCreate
*
@ -343,14 +311,14 @@ public abstract class BaseGenericObjectPool<T> 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 <code>borrowObject()</code> method. Validation is
* performed by the <code>validateObject()</code> method of the factory
* associated with the pool. If the object fails to validate, then
* {@code borrowObject()} will fail.
* <code>borrowObject()</code> will fail.
*
* @param testOnCreate {@code true} if newly created objects should be
* @param testOnCreate <code>true</code> if newly created objects should be
* validated before being returned from the
* {@code borrowObject()} method
* <code>borrowObject()</code> method
*
* @see #getTestOnCreate
*
@ -362,14 +330,14 @@ public abstract class BaseGenericObjectPool<T> 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 <code>borrowObject()</code> method. Validation is
* performed by the <code>validateObject()</code> 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 <code>true</code> if objects are validated before being returned
* from the <code>borrowObject()</code> method
*
* @see #setTestOnBorrow
*/
@ -379,15 +347,15 @@ public abstract class BaseGenericObjectPool<T> 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 <code>borrowObject()</code> method. Validation is
* performed by the <code>validateObject()</code> 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 <code>true</code> if objects should be validated
* before being returned from the
* {@code borrowObject()} method
* <code>borrowObject()</code> method
*
* @see #getTestOnBorrow
*/
@ -397,13 +365,13 @@ public abstract class BaseGenericObjectPool<T> 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 <code>returnObject()</code> method.
* Validation is performed by the <code>validateObject()</code> 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 <code>true</code> if objects are validated on return to
* the pool via the <code>returnObject()</code> method
*
* @see #setTestOnReturn
*/
@ -413,14 +381,14 @@ public abstract class BaseGenericObjectPool<T> 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 <code>returnObject()</code> method.
* Validation is performed by the <code>validateObject()</code> 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 <code>true</code> if objects are validated on
* return to the pool via the
* {@code returnObject()} method
* <code>returnObject()</code> method
*
* @see #getTestOnReturn
*/
@ -432,11 +400,11 @@ public abstract class BaseGenericObjectPool<T> 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 <code>validateObject()</code> 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 <code>true</code> if objects will be validated by the evictor
*
* @see #setTestWhileIdle
* @see #setTimeBetweenEvictionRunsMillis
@ -449,14 +417,14 @@ public abstract class BaseGenericObjectPool<T> 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 <code>validateObject()</code> 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.
* <code>timeBetweenEvictionRunsMillis</code> to a positive value.
*
* @param testWhileIdle
* {@code true} so objects will be validated by the evictor
* <code>true</code> so objects will be validated by the evictor
*
* @see #getTestWhileIdle
* @see #setTimeBetweenEvictionRunsMillis
@ -479,11 +447,9 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
}
/**
* Sets the number of milliseconds to sleep between runs of the idle object evictor thread.
* <ul>
* <li>When positive, the idle object evictor thread starts.</li>
* <li>When non-positive, no idle object evictor thread runs.</li>
* </ul>
* 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<T> extends BaseObject {
* number of idle instances in the pool. When negative, the number of tests
* performed will be <code>ceil({@link #getNumIdle}/
* abs({@link #getNumTestsPerEvictionRun}))</code> which means that when the
* value is {@code -n} roughly one nth of the idle objects will be
* value is <code>-n</code> 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<T> extends BaseObject {
* number of idle instances in the pool. When negative, the number of tests
* performed will be <code>ceil({@link #getNumIdle}/
* abs({@link #getNumTestsPerEvictionRun}))</code> which means that when the
* value is {@code -n} roughly one nth of the idle objects will be
* value is <code>-n</code> roughly one nth of the idle objects will be
* tested per run.
*
* @param numTestsPerEvictionRun
@ -573,7 +539,7 @@ public abstract class BaseGenericObjectPool<T> 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 <code>minIdle</code> 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<T> 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 <code>minIdle</code> 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<T> 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<T> 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<T> evicPolicy = (EvictionPolicy<T>) 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<T>) 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<T> extends BaseObject {
/**
* Has this pool instance been closed.
* @return {@code true} when this pool has been closed.
* @return <code>true</code> when this pool has been closed.
*/
public final boolean isClosed() {
return closed;
}
/**
* <p>Perform {@code numTests} idle object eviction tests, evicting
* <p>Perform <code>numTests</code> idle object eviction tests, evicting
* examined objects that meet the criteria for eviction. If
* {@code testWhileIdle} is true, examined objects are validated
* <code>testWhileIdle</code> 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 <code>minEvicableIdleTimeMillis</code>
* are removed.</p>
*
* @throws Exception when there is a problem evicting idle objects.
@ -755,9 +699,8 @@ public abstract class BaseGenericObjectPool<T> extends BaseObject {
*
* @return the eviction policy
* @since 2.4
* @since 2.6.0 Changed access from protected to public.
*/
public EvictionPolicy<T> getEvictionPolicy() {
protected EvictionPolicy<T> getEvictionPolicy() {
return evictionPolicy;
}
@ -783,33 +726,18 @@ public abstract class BaseGenericObjectPool<T> 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<T> 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 <code>null</code> 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<T> 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 <code>borrowObject()</code> over the lifetime of the
* pool.
* @return validation destroyed object count
*/
@ -946,7 +874,7 @@ public abstract class BaseGenericObjectPool<T> 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 <code>null</code> for no listener
*/
public final SwallowedExceptionListener getSwallowedExceptionListener() {
return swallowedExceptionListener;
@ -956,7 +884,7 @@ public abstract class BaseGenericObjectPool<T> 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 <code>null</code>
* for no listener
*/
public final void setSwallowedExceptionListener(
@ -968,9 +896,9 @@ public abstract class BaseGenericObjectPool<T> 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<T> 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<T> 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<T> 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<T> extends BaseObject {
/**
* Registers the pool with the platform MBean server.
* The registered name will be
* {@code jmxNameBase + jmxNamePrefix + i} where i is the least
* <code>jmxNameBase + jmxNamePrefix + i</code> 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<T> extends BaseObject {
* @param jmxNamePrefix name prefix
* @return registered ObjectName, null if registration fails
*/
private ObjectName jmxRegister(final BaseObjectPoolConfig<T> 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<T> 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<T> 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<T> 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<T> 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<T> 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<T> extends BaseObject {
builder.append(swallowedExceptionListener);
}
}

46
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.
* <p>
* This class is not thread-safe.
* </p>
*
* @param <T> Type of element pooled.
* @since 2.0
*/
public abstract class BaseObjectPoolConfig<T> 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<T> 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 <code>null</code>
* 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<T> 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<T> extends BaseObject implements Clon
private int numTestsPerEvictionRun =
DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
private EvictionPolicy<T> 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<T> 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<T> 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<T> 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<T> 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<T> 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 <code>null</code> 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<T> 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 <code>null</code> means that the pool will define
* the JMX name base.
*
* @param jmxNameBase The new setting of {@code jmxNameBase}

14
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);
}
/**

2
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()}
* </ul>
* <p>
* This class is immutable and thread-safe.
* </p>
*
* @param <T> the type of objects in the pool
*

23
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.
* <p>
* This class is intended to be thread-safe.
* </p>
*
* @param <T> the type of object in the pool
*
@ -48,7 +47,7 @@ public class DefaultPooledObject<T> implements PooledObject<T> {
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<T> implements PooledObject<T> {
@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<T> implements PooledObject<T> {
}
/**
* 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<T> implements PooledObject<T> {
/**
* 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<T> implements PooledObject<T> {
* 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:'",

6
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;
}
/**

10
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}
* <code>yyyy-MM-dd HH:mm:ss Z</code>
*/
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
* <code>yyyy-MM-dd HH:mm:ss Z</code>
*/
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
* <code>yyyy-MM-dd HH:mm:ss Z</code>
*/
String getLastReturnTimeFormatted();

1
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.
* <p>
* This class is immutable and thread-safe.
* </p>
*
* @since 2.0
*/

7
fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/impl/EvictionPolicy.java

@ -37,8 +37,9 @@ public interface EvictionPolicy<T> {
* @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 <code>true</code> if the object should be evicted, otherwise
* <code>false</code>
*/
boolean evict(EvictionConfig config, PooledObject<T> underTest, int idleCount);
boolean evict(EvictionConfig config, PooledObject<T> underTest,
int idleCount);
}

175
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.
* <p>
* 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.
* </p>
* 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.
* <p>
* This class has package scope to prevent its inclusion in the pool public API. The class declaration below should
* *not* be changed to public.
* </p>
* This class has package scope to prevent its inclusion in the pool public API.
* The class declaration below should *not* be changed to public.
* <p>
* This class is intended to be thread-safe.
* </p>
*
* @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<WeakReference<Runnable>, 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<Runnable> 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<WeakReference<Runnable>, 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<Void>) () -> {
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<WeakReference<Runnable>, 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<Void>() {
@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<Runnable> ref;
/**
* Constructs a new instance to track the given reference.
*
* @param ref the reference to track.
*/
private WeakRunner(final WeakReference<Runnable> 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;
}
}
}

277
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 <code>KeyedObjectPool</code> implementation.
* <p>
* 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
* <code>GenericKeyedObjectPool</code> provides robust pooling functionality for
* keyed objects. A <code>GenericKeyedObjectPool</code> 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.}
* </p>
* key to be managed by the containing <code>GenericKeyedObjectPool.</code>
* <p>
* 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.
* </p>
* <p>
* 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.
* </p>
* <p>
* 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.
* </p>
* <p>
* This class is intended to be thread-safe.
* </p>
*
* @see GenericObjectPool
*
@ -83,20 +77,20 @@ import com.fr.third.org.apache.commons.pool2.SwallowedExceptionListener;
*
* @since 2.0
*/
public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
implements KeyedObjectPool<K, T>, GenericKeyedObjectPoolMXBean<K> {
public class GenericKeyedObjectPool<K,T> extends BaseGenericObjectPool<T>
implements KeyedObjectPool<K,T>, GenericKeyedObjectPoolMXBean<K> {
/**
* Create a new {@code GenericKeyedObjectPool} using defaults from
* Create a new <code>GenericKeyedObjectPool</code> using defaults from
* {@link GenericKeyedObjectPoolConfig}.
* @param factory the factory to be used to create entries
*/
public GenericKeyedObjectPool(final KeyedPooledObjectFactory<K, T> factory) {
this(factory, new GenericKeyedObjectPoolConfig<T>());
public GenericKeyedObjectPool(final KeyedPooledObjectFactory<K,T> factory) {
this(factory, new GenericKeyedObjectPoolConfig());
}
/**
* Create a new {@code GenericKeyedObjectPool} using a specific
* Create a new <code>GenericKeyedObjectPool</code> using a specific
* configuration.
*
* @param factory the factory to be used to create entries
@ -105,8 +99,8 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
* the configuration object will not be reflected in the
* pool.
*/
public GenericKeyedObjectPool(final KeyedPooledObjectFactory<K, T> factory,
final GenericKeyedObjectPoolConfig<T> config) {
public GenericKeyedObjectPool(final KeyedPooledObjectFactory<K,T> factory,
final GenericKeyedObjectPoolConfig config) {
super(config, ONAME_BASE, config.getJmxNamePrefix());
@ -118,6 +112,8 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
this.fairness = config.getFairness();
setConfig(config);
startEvictor(getTimeBetweenEvictionRunsMillis());
}
/**
@ -242,12 +238,26 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
*
* @see GenericKeyedObjectPoolConfig
*/
public void setConfig(final GenericKeyedObjectPoolConfig<T> 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<K, T> extends BaseGenericObjectPool<T>
* 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
* <code>true</code> 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.
* <p>
@ -288,24 +298,24 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
* 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
* <code>borrowMaxWaitMillis</code> 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
* <code>maxTotalPerKey</code> and the total number of instances in
* circulation (under all keys) is less than <code>maxTotal</code>, 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 <code>NoSuchElementException</code>
* will be thrown.
* <p>
* 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}
* <code>NoSuchElementException</code>
* ({@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 <code>borrowMaxWait</code> parameter.
* <p>
* When {@code maxTotal} is set to a positive value and this method is
* When <code>maxTotal</code> 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<K, T> extends BaseGenericObjectPool<T>
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<K, T> extends BaseGenericObjectPool<T>
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<K, T> extends BaseGenericObjectPool<T>
}
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<K, T> extends BaseGenericObjectPool<T>
final ObjectDeque<T> objectDeque = poolMap.get(key);
if (objectDeque == null) {
throw new IllegalStateException(
"No keyed pool found under the given key.");
}
final PooledObject<T> p = objectDeque.getAllObjects().get(new IdentityWrapper<>(obj));
final PooledObject<T> p = objectDeque.getAllObjects().get(new IdentityWrapper<T>(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<K, T> extends BaseGenericObjectPool<T>
} 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<K, T> extends BaseGenericObjectPool<T>
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<K, T> extends BaseGenericObjectPool<T>
}
}
/**
* 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<PooledObject<T>> idleObjects) {
if (idleObjects.hasTakeWaiters()) {
try {
addObject(key);
} catch (final Exception e) {
swallowException(e);
}
}
}
/**
* {@inheritDoc}
* <p>
* 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 <code>obj.</code>
*
* @param key pool key
* @param obj instance to invalidate
@ -560,38 +572,17 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
*/
@Override
public void invalidateObject(final K key, final T obj) throws Exception {
invalidateObject(key, obj, DestroyMode.NORMAL);
}
/**
* {@inheritDoc}
* <p>
* 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<T> objectDeque = poolMap.get(key);
final PooledObject<T> p = objectDeque.getAllObjects().get(new IdentityWrapper<>(obj));
final PooledObject<T> p = objectDeque.getAllObjects().get(new IdentityWrapper<T>(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<K, T> extends BaseGenericObjectPool<T>
/**
* Clears the specified sub-pool, removing all pooled instances
* corresponding to the given {@code key}. Exceptions encountered
* corresponding to the given <code>key</code>. Exceptions encountered
* destroying idle instances are swallowed but notified via a
* {@link SwallowedExceptionListener}.
*
@ -649,7 +640,7 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
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<K, T> extends BaseGenericObjectPool<T>
// 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<K, T> extends BaseGenericObjectPool<T>
public void clearOldest() {
// build sorted map of idle objects
final Map<PooledObject<T>, K> map = new TreeMap<>();
final Map<PooledObject<T>, K> map = new TreeMap<PooledObject<T>, K>();
for (final Map.Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
for (final Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
final K k = entry.getKey();
final ObjectDeque<T> deque = entry.getValue();
// Protect against possible NPE if key has been removed in another
@ -768,11 +759,11 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
// 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<Map.Entry<PooledObject<T>, K>> iter =
final Iterator<Entry<PooledObject<T>, K>> iter =
map.entrySet().iterator();
while (iter.hasNext() && itemsToRemove > 0) {
final Map.Entry<PooledObject<T>, K> entry = iter.next();
final Entry<PooledObject<T>, 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<K, T> extends BaseGenericObjectPool<T>
// 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<K, T> extends BaseGenericObjectPool<T>
int maxQueueLength = 0;
LinkedBlockingDeque<PooledObject<T>> mostLoaded = null;
K loadedKey = null;
for (final Map.Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
for (final Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
final K k = entry.getKey();
final ObjectDeque<T> deque = entry.getValue();
if (deque != null) {
@ -850,7 +841,7 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
* {@code false}
*/
private boolean hasBorrowWaiters() {
for (final Map.Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
for (final Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
final ObjectDeque<T> deque = entry.getValue();
if (deque != null) {
final LinkedBlockingDeque<PooledObject<T>> pool =
@ -894,7 +885,7 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
if(evictionIterator == null || !evictionIterator.hasNext()) {
if (evictionKeyIterator == null ||
!evictionKeyIterator.hasNext()) {
final List<K> keyCopy = new ArrayList<>();
final List<K> keyCopy = new ArrayList<K>();
final Lock readLock = keyLock.readLock();
readLock.lock();
try {
@ -959,7 +950,7 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
}
if (evict) {
destroy(evictionKey, underTest, true, DestroyMode.NORMAL);
destroy(evictionKey, underTest, true);
destroyedByEvictorCount.incrementAndGet();
} else {
if (testWhileIdle) {
@ -968,18 +959,18 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
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<K, T> extends BaseGenericObjectPool<T>
PooledObject<T> 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<K, T> extends BaseGenericObjectPool<T>
}
createdCount.incrementAndGet();
objectDeque.getAllObjects().put(new IdentityWrapper<>(p.getObject()), p);
objectDeque.getAllObjects().put(new IdentityWrapper<T>(p.getObject()), p);
return p;
}
@ -1099,33 +1085,23 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
* @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<T> toDestroy, final boolean always, final DestroyMode mode)
private boolean destroy(final K key, final PooledObject<T> toDestroy, final boolean always)
throws Exception {
final ObjectDeque<T> 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<T>(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<K, T> extends BaseGenericObjectPool<T>
lock.lock();
objectDeque = poolMap.get(k);
if (objectDeque == null) {
objectDeque = new ObjectDeque<>(fairness);
objectDeque = new ObjectDeque<T>(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<K, T> extends BaseGenericObjectPool<T>
* @param k The key to de-register
*/
private void deregister(final K k) {
Lock lock = keyLock.readLock();
try {
lock.lock();
final ObjectDeque<T> 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<T> 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<K, T> extends BaseGenericObjectPool<T>
/**
* 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
* <code>addObject</code> 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<K, T> extends BaseGenericObjectPool<T>
@Override
public Map<String,Integer> getNumActivePerKey() {
final HashMap<String,Integer> result = new HashMap<>();
final HashMap<String,Integer> result = new HashMap<String, Integer>();
final Iterator<Entry<K,ObjectDeque<T>>> iter = poolMap.entrySet().iterator();
while (iter.hasNext()) {
@ -1432,9 +1407,9 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
*/
@Override
public Map<String,Integer> getNumWaitersByKey() {
final Map<String,Integer> result = new HashMap<>();
final Map<String,Integer> result = new HashMap<String, Integer>();
for (final Map.Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
for (final Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
final K k = entry.getKey();
final ObjectDeque<T> deque = entry.getValue();
if (deque != null) {
@ -1463,14 +1438,14 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
@Override
public Map<String,List<DefaultPooledObjectInfo>> listAllObjects() {
final Map<String,List<DefaultPooledObjectInfo>> result =
new HashMap<>();
new HashMap<String, List<DefaultPooledObjectInfo>>();
for (final Map.Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
for (final Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) {
final K k = entry.getKey();
final ObjectDeque<T> deque = entry.getValue();
if (deque != null) {
final List<DefaultPooledObjectInfo> list =
new ArrayList<>();
new ArrayList<DefaultPooledObjectInfo>();
result.put(k.toString(), list);
for (final PooledObject<T> p : deque.getAllObjects().values()) {
list.add(new DefaultPooledObjectInfo(p));
@ -1506,7 +1481,7 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
* they work properly as keys.
*/
private final Map<IdentityWrapper<S>, PooledObject<S>> allObjects =
new ConcurrentHashMap<>();
new ConcurrentHashMap<IdentityWrapper<S>, PooledObject<S>>();
/*
* Number of threads with registered interest in this key.
@ -1522,7 +1497,7 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
* will be served as if waiting in a FIFO queue.
*/
public ObjectDeque(final boolean fairness) {
idleObjects = new LinkedBlockingDeque<>(fairness);
idleObjects = new LinkedBlockingDeque<PooledObject<S>>(fairness);
}
/**
@ -1586,7 +1561,7 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
GenericKeyedObjectPoolConfig.DEFAULT_MIN_IDLE_PER_KEY;
private volatile int maxTotalPerKey =
GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL_PER_KEY;
private final KeyedPooledObjectFactory<K, T> factory;
private final KeyedPooledObjectFactory<K,T> factory;
private final boolean fairness;
@ -1597,15 +1572,15 @@ public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
* 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<K, ObjectDeque<T>> poolMap =
new ConcurrentHashMap<>(); // @GuardedBy("keyLock") for write access (and some read access)
private final Map<K,ObjectDeque<T>> poolMap =
new ConcurrentHashMap<K, ObjectDeque<T>>(); // @GuardedBy("keyLock") for write access (and some read access)
/*
* List of pool keys - used to control eviction order. The list of keys
* <b>must</b> 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<K> poolKeyList = new ArrayList<>(); // @GuardedBy("keyLock")
private final List<K> poolKeyList = new ArrayList<K>(); // @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<K, T> extends BaseGenericObjectPool<T>
// 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) {

9
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;
* <p>
* This class is not thread-safe; it is only intended to be used to provide
* attributes used when creating a pool.
* </p>
*
* @param <T> Type of element pooled.
* @since 2.0
*/
public class GenericKeyedObjectPoolConfig<T> extends BaseObjectPoolConfig<T> {
public class GenericKeyedObjectPoolConfig extends BaseObjectPoolConfig {
/**
* The default value for the {@code maxTotalPerKey} configuration attribute.
@ -173,11 +171,10 @@ public class GenericKeyedObjectPoolConfig<T> extends BaseObjectPoolConfig<T> {
this.maxIdlePerKey = maxIdlePerKey;
}
@SuppressWarnings("unchecked")
@Override
public GenericKeyedObjectPoolConfig<T> clone() {
public GenericKeyedObjectPoolConfig clone() {
try {
return (GenericKeyedObjectPoolConfig<T>) super.clone();
return (GenericKeyedObjectPoolConfig) super.clone();
} catch (final CloneNotSupportedException e) {
throw new AssertionError(); // Can't happen
}

35
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<K> {
// 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<String,Integer> 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<String,Integer> getNumWaitersByKey();
/**
* See {@link GenericKeyedObjectPool#listAllObjects()}
* @return See {@link GenericKeyedObjectPool#listAllObjects()}

260
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.
* <p>
* When coupled with the appropriate {@link PooledObjectFactory},
* {@code GenericObjectPool} provides robust pooling functionality for
* arbitrary objects.
* </p>
* <code>GenericObjectPool</code> provides robust pooling functionality for
* arbitrary objects.</p>
* <p>
* 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.
* </p>
* result.</p>
* <p>
* 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
* <code>borrowObject</code> 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 <code>getLastUsed</code> method on that interface; otherwise
* abandonment is determined by how long an object has been checked out from
* the pool.
* </p>
* the pool.</p>
* <p>
* 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.
* </p>
* block. See POOL-125 and DBCP-44 for more information.</p>
* <p>
* This class is intended to be thread-safe.
* </p>
* This class is intended to be thread-safe.</p>
*
* @see GenericKeyedObjectPool
*
@ -84,18 +78,18 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
implements ObjectPool<T>, GenericObjectPoolMXBean, UsageTracking<T> {
/**
* Creates a new {@code GenericObjectPool} using defaults from
* Create a new <code>GenericObjectPool</code> 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<T> factory) {
this(factory, new GenericObjectPoolConfig<T>());
this(factory, new GenericObjectPoolConfig());
}
/**
* Creates a new {@code GenericObjectPool} using a specific
* Create a new <code>GenericObjectPool</code> using a specific
* configuration.
*
* @param factory The object factory to be used to create object instances
@ -106,7 +100,7 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
* pool.
*/
public GenericObjectPool(final PooledObjectFactory<T> factory,
final GenericObjectPoolConfig<T> config) {
final GenericObjectPoolConfig config) {
super(config, ONAME_BASE, config.getJmxNamePrefix());
@ -116,13 +110,15 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
}
this.factory = factory;
idleObjects = new LinkedBlockingDeque<>(config.getFairness());
idleObjects = new LinkedBlockingDeque<PooledObject<T>>(config.getFairness());
setConfig(config);
startEvictor(getTimeBetweenEvictionRunsMillis());
}
/**
* Creates a new {@code GenericObjectPool} that tracks and destroys
* Create a new <code>GenericObjectPool</code> 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<T> extends BaseGenericObjectPool<T>
* and removal. The configuration is used by value.
*/
public GenericObjectPool(final PooledObjectFactory<T> factory,
final GenericObjectPoolConfig<T> config, final AbandonedConfig abandonedConfig) {
final GenericObjectPoolConfig config, final AbandonedConfig abandonedConfig) {
this(factory, config);
setAbandonedConfig(abandonedConfig);
}
@ -188,7 +184,6 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
* <p>
* If the configured value of minIdle is greater than the configured value
* for maxIdle then the value of maxIdle will be used instead.
* </p>
*
* @param minIdle
* The minimum number of objects.
@ -210,7 +205,6 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
* <p>
* If the configured value of minIdle is greater than the configured value
* for maxIdle then the value of maxIdle will be used instead.
* </p>
*
* @return The minimum number of objects.
*
@ -228,7 +222,7 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
}
/**
* 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<T> extends BaseGenericObjectPool<T>
}
/**
* 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<T> extends BaseGenericObjectPool<T>
}
/**
* 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<T> extends BaseGenericObjectPool<T>
}
/**
* 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<T> extends BaseGenericObjectPool<T>
}
/**
* 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<T> extends BaseGenericObjectPool<T>
*
* @see GenericObjectPoolConfig
*/
public void setConfig(final GenericObjectPoolConfig<T> 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<T> extends BaseGenericObjectPool<T>
*
* @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<T> extends BaseGenericObjectPool<T>
}
/**
* 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<T> extends BaseGenericObjectPool<T>
* borrowObject}({@link #getMaxWaitMillis()})</code>.
* <p>
* {@inheritDoc}
* </p>
*/
@Override
public T borrowObject() throws Exception {
@ -357,43 +363,39 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
}
/**
* 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.
* <p>
* 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 <code>true</code> 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.
* </p>
* <p>
* 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
* <code>borrowMaxWaitMillis</code> parameter. If the number of instances
* checked out from the pool is less than <code>maxTotal,</code> 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 <code>NoSuchElementException</code>
* is thrown.
* </p>
* <p>
* 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
* <code>NoSuchElementException</code> (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 <code>borrowMaxWaitMillis</code>
* parameter.
* </p>
* <p>
* 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.
* </p>
*
* @param borrowMaxWaitMillis The time to wait in milliseconds for an object
* to become available
@ -460,7 +462,7 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
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<T> extends BaseGenericObjectPool<T>
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<T> extends BaseGenericObjectPool<T>
}
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<T> extends BaseGenericObjectPool<T>
* 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.
* </p>
* <p>
* 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.
* </p>
* <p>
* Exceptions encountered destroying objects for any reason are swallowed
* but notified via a {@link SwallowedExceptionListener}.
* </p>
*/
@Override
public void returnObject(final T obj) {
final PooledObject<T> p = allObjects.get(new IdentityWrapper<>(obj));
final PooledObject<T> p = allObjects.get(new IdentityWrapper<T>(obj));
if (p == null) {
if (!isAbandonedConfig()) {
@ -534,23 +533,32 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
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<T> extends BaseGenericObjectPool<T>
} 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<T> extends BaseGenericObjectPool<T>
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<T> extends BaseGenericObjectPool<T>
* {@inheritDoc}
* <p>
* Activation of this method decrements the active count and attempts to
* destroy the instance, using the default (NORMAL) {@link DestroyMode}.
* </p>
* destroy the instance.
*
* @throws Exception if an exception occurs destroying the
* object
@ -617,24 +619,7 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
*/
@Override
public void invalidateObject(final T obj) throws Exception {
invalidateObject(obj, DestroyMode.NORMAL);
}
/**
* {@inheritDoc}
* <p>
* Activation of this method decrements the active count and attempts to
* destroy the instance, using the provided {@link DestroyMode}.
* </p>
*
* @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<T> p = allObjects.get(new IdentityWrapper<>(obj));
final PooledObject<T> p = allObjects.get(new IdentityWrapper<T>(obj));
if (p == null) {
if (isAbandonedConfig()) {
return;
@ -644,7 +629,7 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
}
synchronized (p) {
if (p.getState() != PooledObjectState.INVALID) {
destroy(p, mode);
destroy(p);
}
}
ensureIdle(1, false);
@ -657,7 +642,6 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
* idle instance.
* <p>
* Implementation notes:
* </p>
* <ul>
* <li>This method does not destroy or effect in any way instances that are
* checked out of the pool when it is invoked.</li>
@ -674,7 +658,7 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
while (p != null) {
try {
destroy(p, DestroyMode.NORMAL);
destroy(p);
} catch (final Exception e) {
swallowException(e);
}
@ -699,7 +683,6 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
* objects destroyed on return.
* <p>
* Destroys idle instances in the pool by invoking {@link #clear()}.
* </p>
*/
@Override
public void close() {
@ -714,7 +697,7 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
// 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<T> extends BaseGenericObjectPool<T>
* <p>
* Successive activations of this method examine objects in sequence,
* cycling through objects in oldest-to-youngest order.
* </p>
*/
@Override
public void evict() throws Exception {
@ -794,7 +776,7 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
}
if (evict) {
destroy(underTest, DestroyMode.NORMAL);
destroy(underTest);
destroyedByEvictorCount.incrementAndGet();
} else {
if (testWhileIdle) {
@ -803,18 +785,18 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
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<T> extends BaseGenericObjectPool<T>
* <p>
* If there are {@link #getMaxTotal()} objects already in circulation
* or in process of being created, this method returns null.
* </p>
*
* @return The new wrapped pooled object
*
@ -866,9 +847,6 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
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<T> extends BaseGenericObjectPool<T>
// 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<T> extends BaseGenericObjectPool<T>
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<T> extends BaseGenericObjectPool<T>
final PooledObject<T> 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<T> extends BaseGenericObjectPool<T>
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<T>) p).setRequireFullStackTrace(ac.getRequireFullStackTrace());
}
}
createdCount.incrementAndGet();
allObjects.put(new IdentityWrapper<>(p.getObject()), p);
allObjects.put(new IdentityWrapper<T>(p.getObject()), p);
return p;
}
@ -945,17 +915,16 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
* 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<T> toDestroy, final DestroyMode mode) throws Exception {
private void destroy(final PooledObject<T> toDestroy) throws Exception {
toDestroy.invalidate();
idleObjects.remove(toDestroy);
allObjects.remove(new IdentityWrapper<>(toDestroy.getObject()));
allObjects.remove(new IdentityWrapper<T>(toDestroy.getObject()));
try {
factory.destroyObject(toDestroy, mode);
factory.destroyObject(toDestroy);
} finally {
destroyedCount.incrementAndGet();
createCount.decrementAndGet();
@ -974,7 +943,6 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
* 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.
* </p>
*
* @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<T> extends BaseGenericObjectPool<T>
}
/**
* 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.
* <p>
* If there is no capacity available to add to the pool, this is a no-op
@ -1025,7 +993,7 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
}
/**
* 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<T> extends BaseGenericObjectPool<T>
}
/**
* 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<T> extends BaseGenericObjectPool<T>
}
/**
* 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<PooledObject<T>> remove = new ArrayList<>();
now - (ac.getRemoveAbandonedTimeout() * 1000L);
final ArrayList<PooledObject<T>> remove = new ArrayList<PooledObject<T>>();
final Iterator<PooledObject<T>> it = allObjects.values().iterator();
while (it.hasNext()) {
final PooledObject<T> pooledObject = it.next();
@ -1088,11 +1055,11 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
final Iterator<PooledObject<T>> itr = remove.iterator();
while (itr.hasNext()) {
final PooledObject<T> 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<T> extends BaseGenericObjectPool<T>
@Override
public void use(final T pooledObject) {
final AbandonedConfig abandonedCfg = this.abandonedConfig;
if (abandonedCfg != null && abandonedCfg.getUseUsageTracking()) {
final PooledObject<T> wrapper = allObjects.get(new IdentityWrapper<>(pooledObject));
final AbandonedConfig ac = this.abandonedConfig;
if (ac != null && ac.getUseUsageTracking()) {
final PooledObject<T> wrapper = allObjects.get(new IdentityWrapper<T>(pooledObject));
wrapper.use();
}
}
@ -1117,7 +1084,7 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
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<T> extends BaseGenericObjectPool<T>
}
/**
* 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<T> extends BaseGenericObjectPool<T>
* 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.
* </p>
*
* @return Information grouped on all the objects in the pool
*/
@Override
public Set<DefaultPooledObjectInfo> listAllObjects() {
final Set<DefaultPooledObjectInfo> result =
new HashSet<>(allObjects.size());
new HashSet<DefaultPooledObjectInfo>(allObjects.size());
for (final PooledObject<T> p : allObjects.values()) {
result.add(new DefaultPooledObjectInfo(p));
}
@ -1193,7 +1159,7 @@ public class GenericObjectPool<T> extends BaseGenericObjectPool<T>
* wrappers used internally by the pool.
*/
private final Map<IdentityWrapper<T>, PooledObject<T>> allObjects =
new ConcurrentHashMap<>();
new ConcurrentHashMap<IdentityWrapper<T>, PooledObject<T>>();
/*
* 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<T> extends BaseGenericObjectPool<T>
// 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;

9
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;
* <p>
* This class is not thread-safe; it is only intended to be used to provide
* attributes used when creating a pool.
* </p>
*
* @param <T> Type of element pooled.
* @since 2.0
*/
public class GenericObjectPoolConfig<T> extends BaseObjectPoolConfig<T> {
public class GenericObjectPoolConfig extends BaseObjectPoolConfig {
/**
* The default value for the {@code maxTotal} configuration attribute.
@ -135,11 +133,10 @@ public class GenericObjectPoolConfig<T> extends BaseObjectPoolConfig<T> {
this.minIdle = minIdle;
}
@SuppressWarnings("unchecked")
@Override
public GenericObjectPoolConfig<T> clone() {
public GenericObjectPoolConfig clone() {
try {
return (GenericObjectPoolConfig<T>) super.clone();
return (GenericObjectPoolConfig) super.clone();
} catch (final CloneNotSupportedException e) {
throw new AssertionError(); // Can't happen
}

40
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()}

1
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.
* <p>
* This class is intended to be thread-safe.
* </p>
*
* @since 2.0
*/

63
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.
* </p>
*
* <p>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.
* </p>
*
* <p>This class and its iterator implement all of the
* <em>optional</em> methods of the {@link Collection} and {@link
* Iterator} interfaces.
* </p>
*
* <p>This class is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
* </p>
*
* @param <E> the type of elements held in this collection
*
@ -225,7 +220,9 @@ class LinkedBlockingDeque<E> extends AbstractQueue<E>
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<E> extends AbstractQueue<E>
return false;
}
final Node<E> f = first;
final Node<E> x = new Node<>(e, null, f);
final Node<E> x = new Node<E>(e, null, f);
first = x;
if (last == null) {
last = x;
@ -276,7 +273,7 @@ class LinkedBlockingDeque<E> extends AbstractQueue<E>
return false;
}
final Node<E> l = last;
final Node<E> x = new Node<>(e, l, null);
final Node<E> x = new Node<E>(e, l, null);
last = x;
if (first == null) {
first = x;
@ -391,7 +388,9 @@ class LinkedBlockingDeque<E> extends AbstractQueue<E>
*/
@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<E> extends AbstractQueue<E>
*/
@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<E> extends AbstractQueue<E>
* 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<E> extends AbstractQueue<E>
* 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<E> extends AbstractQueue<E>
*/
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<E> extends AbstractQueue<E>
*/
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<E> extends AbstractQueue<E>
}
/**
* 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<E> extends AbstractQueue<E>
}
/**
* 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<E> extends AbstractQueue<E>
* @throws IllegalArgumentException if c is this instance
*/
public int drainTo(final Collection<? super E> 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<E> extends AbstractQueue<E>
public void clear() {
lock.lock();
try {
for (Node<E> f = first; f != null;) {
for (Node<E> f = first; f != null; ) {
f.item = null;
final Node<E> n = f.next;
f.prev = null;
@ -1319,7 +1330,7 @@ class LinkedBlockingDeque<E> extends AbstractQueue<E>
}
/**
* 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<E> extends AbstractQueue<E>
}
/**
* 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<E> extends AbstractQueue<E>
// 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<E> extends AbstractQueue<E>
}
/**
* 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<E> extends AbstractQueue<E>
}
/**
* 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();

8
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;
}

122
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<? extends PooledObjectFactory> factoryClass) {
final Class<PooledObjectFactory> 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<? extends PooledObjectFactory> 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 <T>
* 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 <T> The interface type
*
* @return concrete type used by the implementation
*/
private static <T> Object getGenericType(final Class<T> type, final Class<? extends T> clazz) {
if (type == null || clazz == null) {
// Error will be logged further up the call stack
return null;
}
private static <T> Object getGenericType(final Class<T> type,
final Class<? extends T> 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<? extends T> superClass = (Class<? extends T>) clazz.getSuperclass();
final
Class<? extends T> superClazz =
(Class<? extends T>) 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 <T>
* The interface type.
* @return the matching parameterized type or null.
*/
private static <T> ParameterizedType getParameterizedType(final Class<T> type, final Class<? extends T> 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<?>) {

9
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>) PrivateSecurityManager::new);
this.securityManager = AccessController.doPrivileged(new PrivilegedAction<PrivateSecurityManager>() {
@Override
public PrivateSecurityManager run() {
return new PrivateSecurityManager();
}
});
}
@Override
@ -97,7 +102,7 @@ public class SecurityManagerCallStack implements CallStack {
*/
private List<WeakReference<Class<?>>> getCallStack() {
final Class<?>[] classes = getClassContext();
final List<WeakReference<Class<?>>> stack = new ArrayList<>(classes.length);
final List<WeakReference<Class<?>>> stack = new ArrayList<WeakReference<Class<?>>>(classes.length);
for (final Class<?> klass : classes) {
stack.add(new WeakReference<Class<?>>(klass));
}

63
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}.
* <p>
* This class is intended to be thread-safe.
* </p>
*
* @param <T>
* Type of element pooled in this pool.
@ -46,10 +45,10 @@ public class SoftReferenceObjectPool<T> extends BaseObjectPool<T> {
/**
* Queue of broken references that might be able to be removed from
* {@code _pool}. This is used to help {@link #getNumIdle()} be more
* <code>_pool</code>. This is used to help {@link #getNumIdle()} be more
* accurate with minimal performance overhead.
*/
private final ReferenceQueue<T> refQueue = new ReferenceQueue<>();
private final ReferenceQueue<T> refQueue = new ReferenceQueue<T>();
/** Count of instances that have been checkout out to pool clients */
private int numActive = 0; // @GuardedBy("this")
@ -63,14 +62,14 @@ public class SoftReferenceObjectPool<T> extends BaseObjectPool<T> {
/** Idle references - waiting to be borrowed */
private final LinkedBlockingDeque<PooledSoftReference<T>> idleReferences =
new LinkedBlockingDeque<>();
new LinkedBlockingDeque<PooledSoftReference<T>>();
/** All references - checked out or waiting to be borrowed. */
private final ArrayList<PooledSoftReference<T>> allReferences =
new ArrayList<>();
new ArrayList<PooledSoftReference<T>>();
/**
* Create a {@code SoftReferenceObjectPool} with the specified factory.
* Create a <code>SoftReferenceObjectPool</code> with the specified factory.
*
* @param factory object factory to use.
*/
@ -79,28 +78,28 @@ public class SoftReferenceObjectPool<T> extends BaseObjectPool<T> {
}
/**
* 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.
* <p>
* 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 <code>makeObject</code>
* 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
* <code>NoSuchElementException</code> is thrown. Exceptions thrown by
* <code>MakeObject</code> are propagated to the caller; but other than
* <code>ThreadDeath</code> or <code>VirtualMachineError</code>, exceptions
* generated by activation, validation or destroy methods are swallowed
* silently.
*
@ -128,7 +127,7 @@ public class SoftReferenceObjectPool<T> extends BaseObjectPool<T> {
obj = factory.makeObject().getObject();
createCount++;
// Do not register with the queue
ref = new PooledSoftReference<>(new SoftReference<>(obj));
ref = new PooledSoftReference<T>(new SoftReference<T>(obj));
allReferences.add(ref);
} else {
ref = idleReferences.pollFirst();
@ -137,7 +136,7 @@ public class SoftReferenceObjectPool<T> extends BaseObjectPool<T> {
// 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<T>(obj));
}
if (null != factory && null != obj) {
try {
@ -175,10 +174,10 @@ public class SoftReferenceObjectPool<T> extends BaseObjectPool<T> {
* <ul>
* <li>the pool is closed</li>
* <li>{@link PooledObjectFactory#validateObject(
* com.fr.third.org.apache.commons.pool2.PooledObject) validation} fails
* org.apache.commons.pool2.PooledObject) validation} fails
* </li>
* <li>{@link PooledObjectFactory#passivateObject(
* com.fr.third.org.apache.commons.pool2.PooledObject) passivation}
* org.apache.commons.pool2.PooledObject) passivation}
* throws an exception</li>
* </ul>
* Exceptions passivating or destroying instances are silently swallowed.
@ -186,8 +185,6 @@ public class SoftReferenceObjectPool<T> extends BaseObjectPool<T> {
*
* @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<T> extends BaseObjectPool<T> {
}
/**
* 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.
* <p>
* 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 <code>makeObject</code> or
* <code>passivate</code> are propagated to the caller. Exceptions
* destroying instances are silently swallowed.
*
* @throws IllegalStateException
@ -277,8 +274,8 @@ public class SoftReferenceObjectPool<T> extends BaseObjectPool<T> {
final T obj = factory.makeObject().getObject();
createCount++;
// Create and register with the queue
final PooledSoftReference<T> ref = new PooledSoftReference<>(
new SoftReference<>(obj, refQueue));
final PooledSoftReference<T> ref = new PooledSoftReference<T>(
new SoftReference<T>(obj, refQueue));
allReferences.add(ref);
boolean success = true;
@ -316,7 +313,7 @@ public class SoftReferenceObjectPool<T> extends BaseObjectPool<T> {
}
/**
* 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<T> extends BaseObjectPool<T> {
}
/**
* 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.
* <p>
* Calling {@link #addObject} or {@link #borrowObject} after invoking this
@ -385,7 +382,7 @@ public class SoftReferenceObjectPool<T> extends BaseObjectPool<T> {
}
/**
* 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<T> extends BaseObjectPool<T> {
}
/**
* 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

1
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.
-->
<!-- $Id$ -->
<html>
<head>
<title>Package Documentation for com.fr.third.org.apache.commons.pool2.impl</title>

2
fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/CglibProxySource.java

@ -47,7 +47,7 @@ public class CglibProxySource<T> implements ProxySource<T> {
enhancer.setSuperclass(superclass);
final CglibProxyHandler<T> proxyInterceptor =
new CglibProxyHandler<>(pooledObject, usageTracking);
new CglibProxyHandler<T>(pooledObject, usageTracking);
enhancer.setCallback(proxyInterceptor);
@SuppressWarnings("unchecked")

2
fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/JdkProxySource.java

@ -53,7 +53,7 @@ public class JdkProxySource<T> implements ProxySource<T> {
@SuppressWarnings("unchecked")
final
T proxy = (T) Proxy.newProxyInstance(classLoader, interfaces,
new JdkProxyHandler<>(pooledObject, usageTracking));
new JdkProxyHandler<T>(pooledObject, usageTracking));
return proxy;
}

6
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<K, V> implements KeyedObjectPool<K, V> {
public class ProxiedKeyedObjectPool<K,V> implements KeyedObjectPool<K,V> {
private final KeyedObjectPool<K, V> pool;
private final KeyedObjectPool<K,V> pool;
private final ProxySource<V> proxySource;
@ -44,7 +44,7 @@ public class ProxiedKeyedObjectPool<K, V> implements KeyedObjectPool<K, V> {
* @param pool The object pool to wrap
* @param proxySource The source of the proxy objects
*/
public ProxiedKeyedObjectPool(final KeyedObjectPool<K, V> pool,
public ProxiedKeyedObjectPool(final KeyedObjectPool<K,V> pool,
final ProxySource<V> proxySource) {
this.pool = pool;
this.proxySource = proxySource;

2
fine-jedis/src/main/java/com/fr/third/org/apache/commons/pool2/proxy/package.html

@ -16,7 +16,7 @@
-->
<html>
<head>
<title>Package Documentation for com.fr.third.org.apache.commons.pool2.proxy</title>
<title>Package Documentation for org.apache.commons.pool2.proxy</title>
</head>
<body>
<p>

100
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/AccessControlLogEntry.java

@ -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<String, String> clientInfo;
private final Map<String, Object> logEntry;
public AccessControlLogEntry(Map<String, Object> 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<String, String> getClientInfo() {
return clientInfo;
}
/**
* @return Generic map containing all key-value pairs returned by the server
*/
public Map<String, Object> 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<String, String> getMapFromRawClientInfo(String clientInfo) {
String[] entries = clientInfo.split(" ");
Map<String, String> 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 + '}';
}
}

53
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/AccessControlUser.java

@ -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<String> flags = new ArrayList<>();
private final List<String> keys = new ArrayList<>();
private final List<String> passwords = new ArrayList<>();
private String commands;
public AccessControlUser() {
}
public void addFlag(String flag) {
flags.add(flag);
}
public List<String> getFlags() {
return flags;
}
public void addKey(String key) {
keys.add(key);
}
public List<String> getKeys() {
return keys;
}
public void addPassword(String password) {
passwords.add(password);
}
public List<String> 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 + '\'' + '}';
}
}

1113
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryClient.java

File diff suppressed because it is too large Load Diff

1715
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedis.java

File diff suppressed because it is too large Load Diff

1333
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BinaryJedisCluster.java

File diff suppressed because it is too large Load Diff

31
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<Object> reply = client.getUnflushedObjectMultiBulkReply();
List<Object> 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);
}

477
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<Jedis, JedisShardInfo> implements
BinaryJedisCommands {
private static final Logger logger = LoggerFactory.getLogger(BinaryShardedJedis.class);
private final byte[][] dummyArray = new byte[0][];
public BinaryShardedJedis(List<JedisShardInfo> shards) {
super(shards);
}
@ -52,19 +37,14 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo> 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<Jedis, JedisShardInfo> 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<Jedis, JedisShardInfo> 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<Jedis, JedisShardInfo> 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<Jedis, JedisShardInfo> implement
}
@Override
public List<byte[]> hvals(final byte[] key) {
public Collection<byte[]> hvals(final byte[] key) {
Jedis j = getShard(key);
return j.hvals(key);
}
@ -345,24 +300,6 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo> implement
return j.hgetAll(key);
}
@Override
public byte[] hrandfield(final byte[] key) {
Jedis j = getShard(key);
return j.hrandfield(key);
}
@Override
public List<byte[]> hrandfield(final byte[] key, final long count) {
Jedis j = getShard(key);
return j.hrandfield(key, count);
}
@Override
public Map<byte[], byte[]> 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<Jedis, JedisShardInfo> implement
return j.lpop(key);
}
@Override
public List<byte[]> 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<Long> 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<byte[]> 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<Jedis, JedisShardInfo> implement
return j.sismember(key, member);
}
@Override
public List<Boolean> 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<Jedis, JedisShardInfo> implement
}
@Override
public List<byte[]> 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<Jedis, JedisShardInfo> 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<Jedis, JedisShardInfo> 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<byte[]> zrange(final byte[] key, final long start, final long stop) {
Jedis j = getShard(key);
@ -588,8 +481,7 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo> 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<Jedis, JedisShardInfo> 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<byte[]> zrandmember(final byte[] key, final long count) {
Jedis j = getShard(key);
return j.zrandmember(key, count);
}
@Override
public Set<Tuple> 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<Jedis, JedisShardInfo> implement
return j.zscore(key, member);
}
@Override
public List<Double> 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<Tuple> 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<Tuple> zpopmin(final byte[] key, final int count) {
Jedis j = getShard(key);
return j.zpopmin(key, count);
}
@Override
public List<byte[]> sort(final byte[] key) {
Jedis j = getShard(key);
@ -715,8 +559,7 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo> implement
}
@Override
public Set<byte[]> zrangeByScore(final byte[] key, final double min, final double max,
final int offset, final int count) {
public Set<byte[]> 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<Jedis, JedisShardInfo> implement
}
@Override
public Set<Tuple> zrangeByScoreWithScores(final byte[] key, final double min, final double max,
final int offset, final int count) {
public Set<Tuple> 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<Jedis, JedisShardInfo> implement
}
@Override
public Set<Tuple> zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max,
final int offset, final int count) {
public Set<Tuple> 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<byte[]> zrangeByScore(final byte[] key, final byte[] min, final byte[] max,
final int offset, final int count) {
public Set<byte[]> 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<Jedis, JedisShardInfo> implement
}
@Override
public Set<byte[]> zrevrangeByScore(final byte[] key, final double max, final double min,
final int offset, final int count) {
public Set<byte[]> 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<Jedis, JedisShardInfo> implement
}
@Override
public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, final double max,
final double min, final int offset, final int count) {
public Set<Tuple> 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<Jedis, JedisShardInfo> implement
}
@Override
public Set<byte[]> zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min,
final int offset, final int count) {
public Set<byte[]> 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<Jedis, JedisShardInfo> implement
}
@Override
public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, final byte[] max,
final byte[] min, final int offset, final int count) {
public Set<Tuple> 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<Jedis, JedisShardInfo> implement
}
@Override
public Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min,
final int offset, final int count) {
public Set<byte[]> 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<Jedis, JedisShardInfo> 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<Jedis, JedisShardInfo> implement
return j.objectIdletime(key);
}
public List<String> 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<Jedis, JedisShardInfo> 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<Jedis, JedisShardInfo> implement
return j.geoadd(key, memberCoordinateMap);
}
@Override
public Long geoadd(byte[] key, GeoAddParams params, Map<byte[], GeoCoordinate> 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<Jedis, JedisShardInfo> 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<Jedis, JedisShardInfo> implement
}
@Override
public List<GeoRadiusResponse> georadius(final byte[] key, final double longitude,
final double latitude, final double radius, final GeoUnit unit) {
public List<GeoRadiusResponse> 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<GeoRadiusResponse> 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<GeoRadiusResponse> georadius(final byte[] key, final double longitude,
final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) {
public List<GeoRadiusResponse> 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<GeoRadiusResponse> 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<GeoRadiusResponse> georadiusByMember(final byte[] key, final byte[] member,
final double radius, final GeoUnit unit) {
public List<GeoRadiusResponse> 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<GeoRadiusResponse> 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<GeoRadiusResponse> georadiusByMember(final byte[] key, final byte[] member,
final double radius, final GeoUnit unit, final GeoRadiusParam param) {
public List<GeoRadiusResponse> 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<GeoRadiusResponse> 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<Map.Entry<byte[], byte[]>> hscan(final byte[] key, final byte[] cursor) {
Jedis j = getShard(key);
@ -1095,8 +881,7 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo> implement
}
@Override
public ScanResult<Map.Entry<byte[], byte[]>> hscan(final byte[] key, final byte[] cursor,
final ScanParams params) {
public ScanResult<Map.Entry<byte[], byte[]>> 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<Jedis, JedisShardInfo> implement
public List<Long> bitfield(final byte[] key, final byte[]... arguments) {
Jedis j = getShard(key);
return j.bitfield(key, arguments);
}
@Override
public List<Long> 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<byte[], byte[]> 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<byte[], byte[]> 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<byte[]> xrange(byte[] key, byte[] start, byte[] end) {
Jedis j = getShard(key);
return j.xrange(key, start, end);
}
@Override
public List<byte[]> xrange(byte[] key, byte[] start, byte[] end, int count) {
Jedis j = getShard(key);
return j.xrange(key, start, end, count);
}
@Override
public List<byte[]> xrevrange(byte[] key, byte[] end, byte[] start) {
Jedis j = getShard(key);
return j.xrevrange(key, end, start);
}
@Override
public List<byte[]> 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<Object> 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<Object> xpending(final byte[] key, final byte[] groupname, final XPendingParams params) {
Jedis j = getShard(key);
return j.xpending(key, groupname, params);
}
@Override
public List<byte[]> 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<byte[]> 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<byte[]> 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<StreamGroupInfo> xinfoGroup(byte[] key) {
Jedis j = getShard(key);
return j.xinfoGroup(key);
}
@Override
public List<Object> xinfoGroupBinary(byte[] key) {
Jedis j = getShard(key);
return j.xinfoGroupBinary(key);
}
@Override
public List<StreamConsumersInfo> xinfoConsumers(byte[] key, byte[] group) {
Jedis j = getShard(key);
return j.xinfoConsumers(key, group);
}
@Override
public List<Object> 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);
}
}

2
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<byte[]> params = new ArrayList<>();
private List<byte[]> params = new ArrayList<byte[]>();
protected BitPosParams() {
}

794
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/BuilderFactory.java

File diff suppressed because it is too large Load Diff

624
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<String, String> hash) {
final Map<byte[], byte[]> bhash = new HashMap<>(hash.size());
final Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>(hash.size());
for (final Entry<String, String> 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<String, String> hash) {
final Map<byte[], byte[]> bhash = new HashMap<>(hash.size());
final Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>(hash.size());
for (final Entry<String, String> 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<String> args = new ArrayList<String>(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<String> args = new ArrayList<String>(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<String, GeoCoordinate> 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<byte[], Double> convertScoreMembersToBinary(final Map<String, Double> scoreMembers) {
HashMap<byte[], Double> binaryScoreMembers = new HashMap<>();
HashMap<byte[], Double> binaryScoreMembers = new HashMap<byte[], Double>();
for (Entry<String, Double> entry : scoreMembers.entrySet()) {
binaryScoreMembers.put(SafeEncoder.encode(entry.getKey()), entry.getValue());
}
@ -1392,7 +1103,7 @@ public class Client extends BinaryClient implements Commands {
private HashMap<byte[], GeoCoordinate> convertMemberCoordinateMapToBinary(
final Map<String, GeoCoordinate> memberCoordinateMap) {
HashMap<byte[], GeoCoordinate> binaryMemberCoordinateMap = new HashMap<>();
HashMap<byte[], GeoCoordinate> binaryMemberCoordinateMap = new HashMap<byte[], GeoCoordinate>();
for (Entry<String, GeoCoordinate> 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<String, String> 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<String, String> hash, final XAddParams params) {
xadd(SafeEncoder.encode(key), encodeStringMap(hash), params);
}
private static Map<byte[], byte[]> encodeStringMap(Map<String, String> map) {
final Map<byte[], byte[]> bhash = new HashMap<>(map.size());
for (final Map.Entry<String, String> 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<String, StreamEntryID>... streams) {
final Map<byte[], byte[]> bhash = new HashMap<>(streams.length);
for (final Entry<String, StreamEntryID> 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<String, StreamEntryID> 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<String, StreamEntryID> 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<String, StreamEntryID>... streams) {
final Map<byte[], byte[]> bhash = new HashMap<>(streams.length);
for (final Entry<String, StreamEntryID> 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<String, StreamEntryID> 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<String, StreamEntryID> 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;
}
}

174
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<byte[]>) readProtocolWithCheckingBroken();
}
@Deprecated
@SuppressWarnings("unchecked")
public List<Object> getRawObjectMultiBulkReply() {
return getUnflushedObjectMultiBulkReply();
flush();
return (List<Object>) readProtocolWithCheckingBroken();
}
@SuppressWarnings("unchecked")
@ -315,8 +282,7 @@ public class Connection implements Closeable {
}
public List<Object> 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<Object> getMany(final int count) {
flush();
final List<Object> responses = new ArrayList<>(count);
final List<Object> responses = new ArrayList<Object>(count);
for (int i = 0; i < count; i++) {
try {
responses.add(readProtocolWithCheckingBroken());

4
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" };

210
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/DefaultJedisClientConfig.java

@ -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());
}
}

228
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/DefaultJedisSocketFactory.java

@ -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() + "}";
}
}

3
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;

9
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;
}
}

57
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 <i>unconverted</i> host.
* @param string String to parse. Must be in <b>"host:port"</b> 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() {

6
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/HostAndPortMapper.java

@ -1,6 +0,0 @@
package com.fr.third.redis.clients.jedis;
public interface HostAndPortMapper {
HostAndPort getHostAndPort(HostAndPort hap);
}

1488
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/Jedis.java

File diff suppressed because it is too large Load Diff

76
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClientConfig.java

@ -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 <code>true</code> - to create a TLS connection. <code>false</code> - 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;
}
}

4935
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisCluster.java

File diff suppressed because it is too large Load Diff

201
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<T> {
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<Jedis> askConnection = new ThreadLocal<Jedis>();
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<T> {
}
}
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<T> {
}
}
return runWithRetries(slot);
return runWithRetries(slot, this.maxAttempts, false, false);
}
public T runWithAnyNode() {
@ -94,125 +85,79 @@ public abstract class JedisClusterCommand<T> {
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 <code>TRUE</code> is returned.
*
* @param attemptsLeft
* @param consecutiveConnectionFailures
* @param doneDeadline
* @return true - if some actions are taken
* <br /> 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);
}
}

124
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<HostAndPort> nodes,
GenericObjectPoolConfig<Jedis> 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<HostAndPort> nodes,
GenericObjectPoolConfig<Jedis> poolConfig, int connectionTimeout, int soTimeout,
String password, String clientName) {
this(nodes, poolConfig, connectionTimeout, soTimeout, null, password, clientName);
}
public JedisClusterConnectionHandler(Set<HostAndPort> nodes,
final GenericObjectPoolConfig<Jedis> poolConfig, int connectionTimeout, int soTimeout,
String user, String password, String clientName) {
this(nodes, poolConfig, connectionTimeout, soTimeout, 0, user, password, clientName);
}
public JedisClusterConnectionHandler(Set<HostAndPort> nodes,
final GenericObjectPoolConfig<Jedis> 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<HostAndPort> nodes,
GenericObjectPoolConfig<Jedis> 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<HostAndPort> nodes,
GenericObjectPoolConfig<Jedis> 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<HostAndPort> nodes,
final GenericObjectPoolConfig<Jedis> 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<HostAndPort> nodes,
final JedisClientConfig seedNodesClientConfig,
final GenericObjectPoolConfig<Jedis> poolConfig,
final JedisClientConfig clusterNodesClientConfig) {
this.cache = new JedisClusterInfoCache(poolConfig, clusterNodesClientConfig);
initializeSlotsCache(nodes, seedNodesClientConfig);
}
public JedisClusterConnectionHandler(Set<HostAndPort> nodes,
final GenericObjectPoolConfig<Jedis> 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<String, JedisPool> getNodes() {
return cache.getNodes();
}
private void initializeSlotsCache(Set<HostAndPort> startNodes, JedisClientConfig clientConfig) {
ArrayList<HostAndPort> startNodeList = new ArrayList<>(startNodes);
Collections.shuffle(startNodeList);
for (HostAndPort hostAndPort : startNodeList) {
try (Jedis jedis = new Jedis(hostAndPort, clientConfig)) {
private void initializeSlotsCache(Set<HostAndPort> 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();
}
}
}
}

15
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisClusterHostAndPortMap.java

@ -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());
}
}

194
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<String, JedisPool> nodes = new HashMap<>();
private final Map<Integer, JedisPool> slots = new HashMap<>();
private final Map<String, JedisPool> nodes = new HashMap<String, JedisPool>();
private final Map<Integer, JedisPool> slots = new HashMap<Integer, JedisPool>();
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<Jedis> 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<Jedis> poolConfig, int timeout) {
public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig, int timeout) {
this(poolConfig, timeout, timeout, null, null);
}
public JedisClusterInfoCache(final GenericObjectPoolConfig<Jedis> poolConfig,
final int connectionTimeout, final int soTimeout, final String password,
final String clientName) {
this(poolConfig, connectionTimeout, soTimeout, null, password, clientName);
}
public JedisClusterInfoCache(final GenericObjectPoolConfig<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Object> hostInfos = (List<Object>) 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<Object> 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<String, JedisPool> getNodes() {
r.lock();
try {
return new HashMap<>(nodes);
return new HashMap<String, JedisPool>(nodes);
} finally {
r.unlock();
}
@ -313,7 +215,7 @@ public class JedisClusterInfoCache {
public List<JedisPool> getShuffledNodesPool() {
r.lock();
try {
List<JedisPool> pools = new ArrayList<>(nodes.values());
List<JedisPool> pools = new ArrayList<JedisPool>(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<Integer> getAssignedSlotArray(List<Object> slotInfo) {
List<Integer> slotNums = new ArrayList<>();
List<Integer> slotNums = new ArrayList<Integer>();
for (int slot = ((Long) slotInfo.get(0)).intValue(); slot <= ((Long) slotInfo.get(1))
.intValue(); slot++) {
slotNums.add(slot);

209
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<Jedis> {
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<Jedis> {
private final AtomicReference<HostAndPort> hostAndPort = new AtomicReference<HostAndPort>();
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<Jedis> 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<Jedis> {
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<Jedis> 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>(jedis);
}
@Override
@ -203,18 +142,16 @@ public class JedisFactory implements PooledObjectFactory<Jedis> {
public boolean validateObject(PooledObject<Jedis> 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;
}
}
}
}

269
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<Jedis> 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<Jedis>(), 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<Jedis>(), new JedisFactory(uri,
Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null));
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(uri,
Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null), new GenericObjectPoolConfig());
} else {
initPool(new GenericObjectPoolConfig<Jedis>(), new JedisFactory(url, Protocol.DEFAULT_PORT,
Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null));
this.internalPool = new GenericObjectPool<Jedis>(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<Jedis>(), new JedisFactory(uri,
Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null, sslSocketFactory,
sslParameters, hostnameVerifier));
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(uri,
Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null, sslSocketFactory, sslParameters,
hostnameVerifier), new GenericObjectPoolConfig());
} else {
initPool(new GenericObjectPoolConfig<Jedis>(), 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<Jedis>(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<Jedis>(), uri);
this(new GenericObjectPoolConfig(), uri);
}
public JedisPool(final URI uri, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this(new GenericObjectPoolConfig<Jedis>(), uri, sslSocketFactory, sslParameters,
hostnameVerifier);
this(new GenericObjectPoolConfig(), uri, sslSocketFactory, sslParameters, hostnameVerifier);
}
public JedisPool(final URI uri, final int timeout) {
this(new GenericObjectPoolConfig<Jedis>(), 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<Jedis>(), uri, timeout, sslSocketFactory, sslParameters,
this(new GenericObjectPoolConfig(), uri, timeout, sslSocketFactory, sslParameters,
hostnameVerifier);
}
public JedisPool(final GenericObjectPoolConfig<Jedis> 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<Jedis>(), host, port, user, password);
}
public JedisPool(final GenericObjectPoolConfig<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> poolConfig, final HostAndPort hostAndPort,
final JedisClientConfig clientConfig) {
super(poolConfig, new JedisFactory(hostAndPort, clientConfig));
}
public JedisPool(final GenericObjectPoolConfig<Jedis> poolConfig, final JedisSocketFactory jedisSocketFactory,
final JedisClientConfig clientConfig) {
super(poolConfig, new JedisFactory(jedisSocketFactory, clientConfig));
}
public JedisPool(final GenericObjectPoolConfig<Jedis> 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<Jedis>(), host, port, ssl);
this(new GenericObjectPoolConfig(), host, port, ssl);
}
public JedisPool(final GenericObjectPoolConfig<Jedis> 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<Jedis> 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<Jedis> 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<Jedis>(), host, port, ssl, sslSocketFactory, sslParameters,
this(new GenericObjectPoolConfig(), host, port, ssl, sslSocketFactory, sslParameters,
hostnameVerifier);
}
public JedisPool(final GenericObjectPoolConfig<Jedis> 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<Jedis> 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<Jedis> poolConfig, final URI uri) {
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri) {
this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT);
}
public JedisPool(final GenericObjectPoolConfig<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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<Jedis> 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);
}
}
}

24
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&lt;Jedis&gt;} instead.
*/
@Deprecated
public class JedisPoolAbstract extends Pool<Jedis> {
/**
* 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<Jedis> poolConfig,
PooledObjectFactory<Jedis> factory) {
public JedisPoolAbstract(GenericObjectPoolConfig poolConfig, PooledObjectFactory<Jedis> factory) {
super(poolConfig, factory);
}
@Override
protected void returnBrokenResource(Jedis resource) {
super.returnBrokenResource(resource);
}
@Override
protected void returnResource(Jedis resource) {
super.returnResource(resource);
}
}

2
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<Jedis> {
public class JedisPoolConfig extends GenericObjectPoolConfig {
public JedisPoolConfig() {
// defaults to make your life with connection pool easier :)
setTestWhileIdle(true);

328
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<Object> 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<Object> 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;
}
}

270
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<Jedis> 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<MasterListener> masterListeners = new HashSet<MasterListener>();
/**
* WARNING: This variable will be changed to {@link java.util.Collection} in upcoming major release.
*/
protected final Set<MasterListener> 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<String> sentinels,
final GenericObjectPoolConfig<Jedis> poolConfig) {
final GenericObjectPoolConfig poolConfig) {
this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE);
}
public JedisSentinelPool(String masterName, Set<String> sentinels) {
this(masterName, sentinels, new GenericObjectPoolConfig<Jedis>(), Protocol.DEFAULT_TIMEOUT, null,
this(masterName, sentinels, new GenericObjectPoolConfig(), Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE);
}
public JedisSentinelPool(String masterName, Set<String> sentinels, String password) {
this(masterName, sentinels, new GenericObjectPoolConfig<Jedis>(), Protocol.DEFAULT_TIMEOUT, password);
}
public JedisSentinelPool(String masterName, Set<String> sentinels, String password, String sentinelPassword) {
this(masterName, sentinels, new GenericObjectPoolConfig<Jedis>(), 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<String> sentinels,
final GenericObjectPoolConfig<Jedis> 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<String> sentinels,
final GenericObjectPoolConfig<Jedis> poolConfig, final int timeout) {
final GenericObjectPoolConfig poolConfig, final int timeout) {
this(masterName, sentinels, poolConfig, timeout, null, Protocol.DEFAULT_DATABASE);
}
public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig<Jedis> poolConfig, final String password) {
final GenericObjectPoolConfig poolConfig, final String password) {
this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, password);
}
public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig<Jedis> 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<String> sentinels,
final GenericObjectPoolConfig<Jedis> 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<String> sentinels,
final GenericObjectPoolConfig<Jedis> 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<String> sentinels,
final GenericObjectPoolConfig<Jedis> 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<String> sentinels,
final GenericObjectPoolConfig<Jedis> 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<String> sentinels,
final GenericObjectPoolConfig<Jedis> 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<String> sentinels,
final GenericObjectPoolConfig<Jedis> 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<String> sentinels,
final GenericObjectPoolConfig<Jedis> 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<String> sentinels,
final GenericObjectPoolConfig<Jedis> 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<String> sentinels,
final GenericObjectPoolConfig<Jedis> 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<String> sentinels,
final GenericObjectPoolConfig<Jedis> 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<String> sentinels,
final GenericObjectPoolConfig<Jedis> 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<String> sentinels,
final GenericObjectPoolConfig<Jedis> poolConfig, final JedisFactory factory) {
this(masterName, parseHostAndPorts(sentinels), poolConfig, factory,
DefaultJedisClientConfig.builder().build());
}
public JedisSentinelPool(String masterName, Set<HostAndPort> sentinels,
final GenericObjectPoolConfig<Jedis> poolConfig, final JedisClientConfig masteClientConfig,
final JedisClientConfig sentinelClientConfig) {
this(masterName, sentinels, poolConfig, new JedisFactory(masteClientConfig), sentinelClientConfig);
}
public JedisSentinelPool(String masterName, Set<HostAndPort> sentinels,
final GenericObjectPoolConfig<Jedis> 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<HostAndPort> parseHostAndPorts(Set<String> 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<HostAndPort> sentinels, final String masterName) {
private HostAndPort initSentinels(Set<String> 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<String> 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<String> masterAddr = j.sentinelGetMasterAddrByName(masterName);
/*
* Added code for active refresh
*/
List<String> 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);
}
}
}
}
}

32
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisShardInfo.java

@ -17,7 +17,6 @@ public class JedisShardInfo extends ShardInfo<Jedis> {
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<Jedis> {
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<Jedis> {
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<Jedis> {
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<Jedis> {
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<Jedis> {
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<Jedis> {
}
public boolean getSsl() {
return ssl;
return ssl;
}
public SSLSocketFactory getSslSocketFactory() {
@ -262,5 +248,5 @@ public class JedisShardInfo extends ShardInfo<Jedis> {
public Jedis createResource() {
return new Jedis(this);
}
}

87
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<HostAndPort> nodes,
final GenericObjectPoolConfig<Jedis> poolConfig, int timeout) {
final GenericObjectPoolConfig poolConfig, int timeout) {
this(nodes, poolConfig, timeout, timeout);
}
public JedisSlotBasedConnectionHandler(Set<HostAndPort> nodes,
final GenericObjectPoolConfig<Jedis> 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<HostAndPort> nodes,
GenericObjectPoolConfig<Jedis> poolConfig, int connectionTimeout, int soTimeout,
String password) {
public JedisSlotBasedConnectionHandler(Set<HostAndPort> nodes, GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, String password) {
super(nodes, poolConfig, connectionTimeout, soTimeout, password);
}
public JedisSlotBasedConnectionHandler(Set<HostAndPort> nodes,
GenericObjectPoolConfig<Jedis> poolConfig, int connectionTimeout, int soTimeout,
String password, String clientName) {
public JedisSlotBasedConnectionHandler(Set<HostAndPort> nodes, GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, String password, String clientName) {
super(nodes, poolConfig, connectionTimeout, soTimeout, password, clientName);
}
public JedisSlotBasedConnectionHandler(Set<HostAndPort> nodes,
GenericObjectPoolConfig<Jedis> poolConfig, int connectionTimeout, int soTimeout, String user,
String password, String clientName) {
super(nodes, poolConfig, connectionTimeout, soTimeout, user, password, clientName);
}
public JedisSlotBasedConnectionHandler(Set<HostAndPort> nodes,
GenericObjectPoolConfig<Jedis> 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<HostAndPort> nodes,
GenericObjectPoolConfig<Jedis> 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<HostAndPort> nodes,
GenericObjectPoolConfig<Jedis> 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<HostAndPort> nodes,
GenericObjectPoolConfig<Jedis> 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<HostAndPort> nodes,
GenericObjectPoolConfig<Jedis> 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<JedisPool> 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();
}
}

55
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/JedisSocketFactory.java

@ -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.
* <p>
* 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);
}

10
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;
}
}
}

369
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<Boolean> copy(byte[] srcKey, byte[] dstKey, int db, boolean replace) {
client.copy(srcKey, dstKey, db, replace);
return getResponse(BuilderFactory.BOOLEAN);
}
@Override
public Response<Boolean> copy(byte[] srcKey, byte[] dstKey, boolean replace) {
client.copy(srcKey, dstKey, replace);
return getResponse(BuilderFactory.BOOLEAN);
}
@Override
public Response<Boolean> copy(String srcKey, String dstKey, int db, boolean replace) {
client.copy(srcKey, dstKey, db, replace);
return getResponse(BuilderFactory.BOOLEAN);
}
@Override
public Response<Boolean> copy(String srcKey, String dstKey, boolean replace) {
client.copy(srcKey, dstKey, replace);
return getResponse(BuilderFactory.BOOLEAN);
}
@Override
public Response<String> lmove(String srcKey, String dstKey, ListDirection from,
ListDirection to) {
client.lmove(srcKey, dstKey, from, to);
return getResponse(BuilderFactory.STRING);
}
@Override
public Response<byte[]> lmove(byte[] srcKey, byte[] dstKey, ListDirection from,
ListDirection to) {
client.lmove(srcKey, dstKey, from, to);
return getResponse(BuilderFactory.BYTE_ARRAY);
}
@Override
public Response<String> blmove(String srcKey, String dstKey, ListDirection from, ListDirection to,
double timeout) {
client.blmove(srcKey, dstKey, from, to, timeout);
return getResponse(BuilderFactory.STRING);
public Response<List<String>> brpop(String... args) {
client.brpop(args);
return getResponse(BuilderFactory.STRING_LIST);
}
@Override
public Response<byte[]> 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<List<String>> 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<List<byte[]>> blpop(byte[]... args) {
client.blpop(args);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
@Override
public Response<List<String>> 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<Map<String, String>> blpopMap(int timeout, String... keys) {
client.blpop(timeout, keys);
return getResponse(BuilderFactory.STRING_MAP);
}
@Deprecated
public Response<List<String>> blpop(int timeout, byte[]... keys) {
client.blpop(timeout, keys);
return getResponse(BuilderFactory.STRING_LIST);
}
@Override
public Response<KeyedListElement> blpop(double timeout, String... keys) {
client.blpop(timeout, keys);
return getResponse(BuilderFactory.KEYED_LIST_ELEMENT);
}
@Override
public Response<List<byte[]>> blpop(double timeout, byte[]... keys) {
client.blpop(timeout, keys);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
@Override
public Response<List<String>> brpop(String... args) {
client.brpop(args);
return getResponse(BuilderFactory.STRING_LIST);
}
@Override
public Response<List<byte[]>> brpop(byte[]... args) {
client.brpop(args);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
@Override
public Response<List<String>> brpop(int timeout, String... keys) {
public Response<List<String>> 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<Map<String, String>> brpopMap(int timeout, String... keys) {
client.blpop(timeout, keys);
return getResponse(BuilderFactory.STRING_MAP);
}
@Deprecated
public Response<List<String>> brpop(int timeout, byte[]... keys) {
client.brpop(timeout, keys);
return getResponse(BuilderFactory.STRING_LIST);
}
@Override
public Response<KeyedListElement> brpop(double timeout, String... keys) {
client.brpop(timeout, keys);
return getResponse(BuilderFactory.KEYED_LIST_ELEMENT);
}
@Override
public Response<List<byte[]>> brpop(double timeout, byte[]... keys) {
client.brpop(timeout, keys);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
@Override
public Response<KeyedZSetElement> bzpopmax(double timeout, String... keys) {
client.bzpopmax(timeout, keys);
return getResponse(BuilderFactory.KEYED_ZSET_ELEMENT);
}
@Override
public Response<List<byte[]>> bzpopmax(double timeout, byte[]... keys) {
client.bzpopmax(timeout, keys);
public Response<List<byte[]>> blpop(byte[]... args) {
client.blpop(args);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
@Override
public Response<KeyedZSetElement> bzpopmin(double timeout, String... keys) {
client.bzpopmin(timeout, keys);
return getResponse(BuilderFactory.KEYED_ZSET_ELEMENT);
}
@Override
public Response<List<byte[]>> bzpopmin(double timeout, byte[]... keys) {
client.bzpopmin(timeout, keys);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
public Response<List<String>> 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<String> unwatch() {
client.unwatch();
return getResponse(BuilderFactory.STRING);
}
@Override
public Response<Set<byte[]>> zdiff(byte[]... keys) {
client.zdiff(keys);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
@Override
public Response<Set<Tuple>> zdiffWithScores(byte[]... keys) {
client.zdiffWithScores(keys);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
@Override
public Response<Set<String>> zdiff(String... keys) {
client.zdiff(keys);
return getResponse(BuilderFactory.STRING_ZSET);
}
@Override
public Response<Set<Tuple>> zdiffWithScores(String... keys) {
client.zdiffWithScores(keys);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
@Override
public Response<Long> zdiffStore(final byte[] dstkey, final byte[]... keys) {
client.zdiffStore(dstkey, keys);
return getResponse(BuilderFactory.LONG);
}
@Override
public Response<Long> zdiffStore(final String dstkey, final String... keys) {
client.zdiffStore(dstkey, keys);
return getResponse(BuilderFactory.LONG);
}
@Override
public Response<Set<byte[]>> zinter(final ZParams params, final byte[]... keys) {
client.zinter(params, keys);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
@Override
public Response<Set<Tuple>> zinterWithScores(final ZParams params, final byte[]... keys) {
client.zinterWithScores(params, keys);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
@Override
public Response<Set<String>> zinter(final ZParams params, final String... keys) {
client.zinter(params, keys);
return getResponse(BuilderFactory.STRING_ZSET);
}
@Override
public Response<Set<Tuple>> zinterWithScores(final ZParams params, final String... keys) {
client.zinterWithScores(params, keys);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
@Override
public Response<Long> 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<Set<byte[]>> zunion(ZParams params, byte[]... keys) {
client.zunion(params, keys);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
}
@Override
public Response<Set<Tuple>> zunionWithScores(ZParams params, byte[]... keys) {
client.zunionWithScores(params, keys);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
@Override
public Response<Set<String>> zunion(ZParams params, String... keys) {
client.zunion(params, keys);
return getResponse(BuilderFactory.STRING_ZSET);
}
@Override
public Response<Set<Tuple>> zunionWithScores(ZParams params, String... keys) {
client.zunionWithScores(params, keys);
return getResponse(BuilderFactory.TUPLE_ZSET);
}
@Override
public Response<Long> 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<String> flushDB(FlushMode flushMode) {
client.flushDB(flushMode);
return getResponse(BuilderFactory.STRING);
}
@Override
public Response<String> flushAll(FlushMode flushMode) {
client.flushAll(flushMode);
return getResponse(BuilderFactory.STRING);
}
@Override
public Response<String> info() {
client.info();
@ -787,7 +568,7 @@ public abstract class MultiKeyPipelineBase extends PipelineBase implements
@Override
public Response<Object> 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<Object> 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<Object> 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<Object> 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<Object> 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<String> moduleLoad(String path) {
client.moduleLoad(path);
return getResponse(BuilderFactory.STRING);
}
@Override
public Response<String> 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<String> 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<Object> sendCommand(final ProtocolCommand cmd, final String... args) {
client.sendCommand(cmd, args);
return getResponse(BuilderFactory.RAW_OBJECT);
}
public Response<Object> sendCommand(final ProtocolCommand cmd, final byte[]... args) {
client.sendCommand(cmd, args);
return getResponse(BuilderFactory.RAW_OBJECT);
}
@Override
public Response<Long> 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<Long> 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<Long> 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<Long> 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<List<byte[]>> xread(int count, long block, Map<byte[], byte[]> streams) {
client.xread(count, block, streams);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
@Override
public Response<List<byte[]>> xread(XReadParams xReadParams, Map.Entry<byte[], byte[]>... streams) {
client.xread(xReadParams, streams);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
@Override
public Response<List<byte[]>> xreadGroup(byte[] groupname, byte[] consumer, int count, long block,
boolean noAck, Map<byte[], byte[]> streams) {
client.xreadGroup(groupname, consumer, count, block, noAck, streams);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
@Override
public Response<List<byte[]>> xreadGroup(final byte[] groupname, final byte[] consumer,
final XReadGroupParams xReadGroupParams, final Map.Entry<byte[], byte[]>... streams) {
client.xreadGroup(groupname, consumer, xReadGroupParams, streams);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
}
@Override
public Response<List<Map.Entry<String, List<StreamEntry>>>> xread(int count, long block,
Map.Entry<String, StreamEntryID>... streams) {
client.xread(count, block, streams);
return getResponse(BuilderFactory.STREAM_READ_RESPONSE);
}
@Override
public Response<List<Map.Entry<String, List<StreamEntry>>>> xread(final XReadParams xReadParams,
final Map<String, StreamEntryID> streams) {
client.xread(xReadParams, streams);
return getResponse(BuilderFactory.STREAM_READ_RESPONSE);
}
@Override
public Response<List<Map.Entry<String, List<StreamEntry>>>> xreadGroup(String groupname,
String consumer, int count, long block, boolean noAck,
Map.Entry<String, StreamEntryID>... streams) {
client.xreadGroup(groupname, consumer, count, block, noAck, streams);
return getResponse(BuilderFactory.STREAM_READ_RESPONSE);
}
@Override
public Response<List<Map.Entry<String, List<StreamEntry>>>> xreadGroup(final String groupname,
final String consumer, final XReadGroupParams xReadGroupParams,
final Map<String, StreamEntryID> streams) {
client.xreadGroup(groupname, consumer, xReadGroupParams, streams);
return getResponse(BuilderFactory.STREAM_READ_RESPONSE);
}
}
}

8
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<List<Object>> {
private List<Response<?>> responses = new ArrayList<>();
private List<Response<?>> responses = new ArrayList<Response<?>>();
@Override
public List<Object> build(Object data) {
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) data;
List<Object> values = new ArrayList<>();
List<Object> values = new ArrayList<Object>();
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<T> lr = new Response<>(builder);
Response<T> lr = new Response<T>(builder);
currentMulti.addResponse(lr);
return lr;
} else {
@ -111,7 +111,7 @@ public class Pipeline extends MultiKeyPipelineBase implements Closeable {
public List<Object> syncAndReturnAll() {
if (getPipelinedResponseLength() > 0) {
List<Object> unformatted = client.getMany(getPipelinedResponseLength());
List<Object> formatted = new ArrayList<>();
List<Object> formatted = new ArrayList<Object>();
for (Object o : unformatted) {
try {
formatted.add(generateResponse(o).get());

866
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/PipelineBase.java

File diff suppressed because it is too large Load Diff

120
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<Object> ret = new ArrayList<>(num);
final List<Object> ret = new ArrayList<Object>(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;
}
}
}

4
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<Response<?>> pipelinedResponses = new LinkedList<>();
private Queue<Response<?>> pipelinedResponses = new LinkedList<Response<?>>();
protected void clean() {
pipelinedResponses.clear();
@ -19,7 +19,7 @@ public class Queable {
}
protected <T> Response<T> getResponse(Builder<T> builder) {
Response<T> lr = new Response<>(builder);
Response<T> lr = new Response<T>(builder);
pipelinedResponses.add(lr);
return lr;
}

14
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<Keyword, ByteBuffer> params = new EnumMap<>(Keyword.class);
private final Map<Keyword, ByteBuffer> params = new EnumMap<Keyword, ByteBuffer>(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 <a href="https://redis.io/commands/scan#the-match-option">MATCH option in Redis documentation</a>
*
* @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 <a href="https://redis.io/commands/scan#the-count-option">COUNT option in Redis documentation</a>
*
* @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<byte[]> getParams() {
List<byte[]> paramsList = new ArrayList<>(params.size());
List<byte[]> paramsList = new ArrayList<byte[]>(params.size());
for (Map.Entry<Keyword, ByteBuffer> param : params.entrySet()) {
paramsList.add(param.getKey().raw);
paramsList.add(param.getValue().array());

1
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/ScanResult.java

@ -27,6 +27,7 @@ public class ScanResult<T> {
/**
* Is the iteration complete. I.e. was the complete dataset scanned.
*
* @return true if the iteration is complete
*/
public boolean isCompleteIteration() {

453
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<String> blpop(final int timeout, final String key) {
Jedis j = getShard(key);
return j.blpop(timeout, key);
public List<String> blpop(final String arg) {
Jedis j = getShard(arg);
return j.blpop(arg);
}
@Override
public KeyedListElement blpop(final double timeout, final String key) {
public List<String> blpop(final int timeout, final String key) {
Jedis j = getShard(key);
return j.blpop(timeout, key);
}
@Override
public List<String> brpop(final int timeout, final String key) {
Jedis j = getShard(key);
return j.brpop(timeout, key);
public List<String> brpop(final String arg) {
Jedis j = getShard(arg);
return j.brpop(arg);
}
@Override
public KeyedListElement brpop(final double timeout, final String key) {
public List<String> 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<String> hrandfield(final String key, final long count) {
Jedis j = getShard(key);
return j.hrandfield(key, count);
}
@Override
public Map<String, String> 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<String> 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<Long> 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<String> 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<Boolean> 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<String> 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<String> zrandmember(final String key, final long count) {
Jedis j = getShard(key);
return j.zrandmember(key, count);
}
@Override
public Set<Tuple> 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<Double> 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<Tuple> 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<Tuple> zpopmin(final String key, final int count) {
Jedis j = getShard(key);
return j.zpopmin(key, count);
}
@Override
public List<String> sort(final String key) {
Jedis j = getShard(key);
@ -751,15 +603,13 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, C
}
@Override
public Set<String> zrangeByScore(final String key, final double min, final double max,
final int offset, final int count) {
public Set<String> 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<String> zrevrangeByScore(final String key, final double max, final double min,
final int offset, final int count) {
public Set<String> 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<Tuple> zrangeByScoreWithScores(final String key, final double min, final double max,
final int offset, final int count) {
public Set<Tuple> 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<Tuple> zrevrangeByScoreWithScores(final String key, final double max,
final double min, final int offset, final int count) {
public Set<Tuple> 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<String> zrangeByScore(final String key, final String min, final String max,
final int offset, final int count) {
public Set<String> 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<String> zrevrangeByScore(final String key, final String max, final String min,
final int offset, final int count) {
public Set<String> 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<Tuple> zrangeByScoreWithScores(final String key, final String min, final String max,
final int offset, final int count) {
public Set<Tuple> 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<Tuple> zrevrangeByScoreWithScores(final String key, final String max,
final String min, final int offset, final int count) {
public Set<Tuple> 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<String> zrevrangeByLex(final String key, final String max, final String min,
final int offset, final int count) {
public Set<String> 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<Entry<String, String>> hscan(final String key, final String cursor,
final ScanParams params) {
public ScanResult<Entry<String, String>> 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<String, GeoCoordinate> 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<GeoRadiusResponse> georadius(final String key, final double longitude,
final double latitude, final double radius, final GeoUnit unit) {
public List<GeoRadiusResponse> 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<GeoRadiusResponse> 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<GeoRadiusResponse> georadius(final String key, final double longitude,
final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) {
public List<GeoRadiusResponse> 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<GeoRadiusResponse> 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<GeoRadiusResponse> georadiusByMember(final String key, final String member,
final double radius, final GeoUnit unit) {
public List<GeoRadiusResponse> 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<GeoRadiusResponse> 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<GeoRadiusResponse> georadiusByMember(final String key, final String member,
final double radius, final GeoUnit unit, final GeoRadiusParam param) {
public List<GeoRadiusResponse> 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<GeoRadiusResponse> 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<Long> bitfield(final String key, final String... arguments) {
Jedis j = getShard(key);
return j.bitfield(key, arguments);
}
@Override
public List<Long> 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<String, String> hash) {
Jedis j = getShard(key);
return j.xadd(key, id, hash);
}
@Override
public StreamEntryID xadd(String key, StreamEntryID id, Map<String, String> 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<String, String> 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<StreamEntry> xrange(String key, StreamEntryID start, StreamEntryID end) {
Jedis j = getShard(key);
return j.xrange(key, start, end);
}
@Override
public List<StreamEntry> 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<StreamEntry> xrevrange(String key, StreamEntryID end, StreamEntryID start) {
Jedis j = getShard(key);
return j.xrevrange(key, end, start);
}
@Override
public List<StreamEntry> 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<StreamPendingEntry> 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<StreamPendingEntry> xpending(String key, String groupname, XPendingParams params) {
Jedis j = getShard(key);
return j.xpending(key, groupname, params);
}
@Override
public List<StreamEntry> 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<StreamEntry> 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<StreamEntryID> 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<StreamGroupInfo> xinfoGroup(String key) {
Jedis j = getShard(key);
return j.xinfoGroup(key);
}
@Override
public List<StreamConsumersInfo> 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);
}
}

17
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<FutureResult> results = new ArrayList<>();
private Queue<Client> clients = new LinkedList<>();
private List<FutureResult> results = new ArrayList<FutureResult>();
private Queue<Client> clients = new LinkedList<Client>();
private static class FutureResult {
private Client client;
@ -32,7 +27,7 @@ public class ShardedJedisPipeline extends PipelineBase {
}
public List<Object> getResults() {
List<Object> r = new ArrayList<>();
List<Object> r = new ArrayList<Object>();
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&lt;?&gt; 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<Object> syncAndReturnAll() {
List<Object> formatted = new ArrayList<>();
List<Object> formatted = new ArrayList<Object>();
for (Client client : clients) {
formatted.add(generateResponse(client.getOne()).get());
}

51
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<ShardedJedis> {
private static final Logger logger = LoggerFactory.getLogger(ShardedJedisPool.class);
public ShardedJedisPool(final GenericObjectPoolConfig<ShardedJedis> poolConfig,
List<JedisShardInfo> shards) {
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, List<JedisShardInfo> shards) {
this(poolConfig, shards, Hashing.MURMUR_HASH);
}
public ShardedJedisPool(final GenericObjectPoolConfig<ShardedJedis> poolConfig,
List<JedisShardInfo> shards, Hashing algo) {
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, List<JedisShardInfo> shards,
Hashing algo) {
this(poolConfig, shards, algo, null);
}
public ShardedJedisPool(final GenericObjectPoolConfig<ShardedJedis> poolConfig,
List<JedisShardInfo> shards, Pattern keyTagPattern) {
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, List<JedisShardInfo> shards,
Pattern keyTagPattern) {
this(poolConfig, shards, Hashing.MURMUR_HASH, keyTagPattern);
}
public ShardedJedisPool(final GenericObjectPoolConfig<ShardedJedis> poolConfig,
List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) {
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, List<JedisShardInfo> shards,
Hashing algo, Pattern keyTagPattern) {
super(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern));
}
@ -45,7 +39,14 @@ public class ShardedJedisPool extends Pool<ShardedJedis> {
}
@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<ShardedJedis> {
* PoolableObjectFactory custom impl.
*/
private static class ShardedJedisFactory implements PooledObjectFactory<ShardedJedis> {
private final List<JedisShardInfo> shards;
private final Hashing algo;
private final Pattern keyTagPattern;
private List<JedisShardInfo> shards;
private Hashing algo;
private Pattern keyTagPattern;
public ShardedJedisFactory(List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) {
this.shards = shards;
@ -70,7 +70,7 @@ public class ShardedJedisPool extends Pool<ShardedJedis> {
@Override
public PooledObject<ShardedJedis> makeObject() throws Exception {
ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern);
return new DefaultPooledObject<>(jedis);
return new DefaultPooledObject<ShardedJedis>(jedis);
}
@Override
@ -79,17 +79,14 @@ public class ShardedJedisPool extends Pool<ShardedJedis> {
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<ShardedJedis> {
}
}
}
}

20
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<byte[]> params = new ArrayList<>();
private List<byte[]> params = new ArrayList<byte[]>();
/**
* 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;

52
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamConsumersInfo.java

@ -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<String, Object> consumerInfo;
/**
* @param map contains key-value pairs with consumer info
*/
public StreamConsumersInfo(Map<String, Object> 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<String, Object> getConsumerInfo() {
return consumerInfo;
}
}

41
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamEntry.java

@ -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<String, String> fields;
public StreamEntry(StreamEntryID id, Map<String, String> fields) {
this.id = id;
this.fields = fields;
}
public StreamEntryID getID() {
return id;
}
public Map<String, String> 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<String, String>) in.readUnshared();
}
}

120
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamEntryID.java

@ -1,120 +0,0 @@
package com.fr.third.redis.clients.jedis;
import java.io.IOException;
import java.io.Serializable;
public class StreamEntryID implements Comparable<StreamEntryID>, Serializable {
private static final long serialVersionUID = 1L;
/**
* Should be used only with XADD
*
* <code>
* XADD mystream * field1 value1
* </code>
*/
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
*
* <code>
* XGROUP CREATE mystream consumer-group-name $
* </code>
*/
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
* <code>
* XREADGROUP $GroupName $ConsumerName BLOCK 2000 COUNT 10 STREAMS mystream >
* </code>
*/
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();
}
}

60
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamGroupInfo.java

@ -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<String, Object> groupInfo;
/**
* @param map contains key-value pairs with group info
*/
public StreamGroupInfo(Map<String, Object> 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<String, Object> getGroupInfo() {
return groupInfo;
}
}

82
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamInfo.java

@ -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<String, Object> streamInfo;
/**
* @param map contains key-value pairs with stream info
*/
public StreamInfo(Map<String, Object> 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<String, Object> getStreamInfo() {
return streamInfo;
}
}

59
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamPendingEntry.java

@ -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();
}
}

38
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/StreamPendingSummary.java

@ -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<String, Long> consumerMessageCount;
public StreamPendingSummary(long total, StreamEntryID minId, StreamEntryID maxId,
Map<String, Long> 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<String, Long> getConsumerMessageCount() {
return consumerMessageCount;
}
}

32
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<Object> formatted = new ArrayList<>();
List<Object> formatted = new ArrayList<Object>();
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<?>> response = new ArrayList<>();
List<Response<?>> response = new ArrayList<Response<?>>();
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<String> 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<String> watch(byte[]... keys) throws UnsupportedOperationException {
throw new UnsupportedOperationException(WATCH_INSIDE_MULTI_MESSAGE);
}
}
}

14
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<Tuple> {
@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<Tuple> {
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<Tuple> {
public String toString() {
return '[' + SafeEncoder.encode(element) + ',' + score + ']';
}
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
}

15
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<byte[]> params = new ArrayList<>();
private List<byte[]> params = new ArrayList<byte[]>();
/**
* 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;
}

30
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/FlushMode.java

@ -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;
}
}

21
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/ListDirection.java

@ -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;
}
}

6
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/Rawable.java

@ -1,6 +0,0 @@
package com.fr.third.redis.clients.jedis.args;
public interface Rawable {
byte[] getRaw();
}

21
fine-jedis/src/main/java/com/fr/third/redis/clients/jedis/args/UnblockType.java

@ -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;
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save