DATAREDIS-254 - Clean up codebase to match spring-data conventions

Format code with spring data formatter.
This commit is contained in:
Christoph Strobl
2014-01-27 14:32:24 +01:00
committed by Thomas Darimont
parent fb2db4ae6f
commit 271d3d197d
249 changed files with 3419 additions and 5253 deletions

View File

@@ -20,7 +20,7 @@ import org.springframework.dao.UncategorizedDataAccessException;
/** /**
* Exception thrown when we can't classify a Redis exception into one of Spring generic data access exceptions. * Exception thrown when we can't classify a Redis exception into one of Spring generic data access exceptions.
* *
* @author Costin Leau * @author Costin Leau
*/ */
public class RedisSystemException extends UncategorizedDataAccessException { public class RedisSystemException extends UncategorizedDataAccessException {

View File

@@ -20,7 +20,8 @@ import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer;
/** /**
* Default implementation for {@link RedisCachePrefix} which uses the given cache name and a delimiter for creating the prefix. * Default implementation for {@link RedisCachePrefix} which uses the given cache name and a delimiter for creating the
* prefix.
* *
* @author Costin Leau * @author Costin Leau
*/ */

View File

@@ -39,8 +39,7 @@ class RedisCache implements Cache {
private static final int PAGE_SIZE = 128; private static final int PAGE_SIZE = 128;
private final String name; private final String name;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes") private final RedisTemplate template;
private final RedisTemplate template;
private final byte[] prefix; private final byte[] prefix;
private final byte[] setName; private final byte[] setName;
private final byte[] cacheLockName; private final byte[] cacheLockName;
@@ -48,9 +47,8 @@ class RedisCache implements Cache {
private final long expiration; private final long expiration;
/** /**
*
* Constructs a new <code>RedisCache</code> instance. * Constructs a new <code>RedisCache</code> instance.
* *
* @param name cache name * @param name cache name
* @param prefix * @param prefix
* @param template * @param template
@@ -76,10 +74,8 @@ class RedisCache implements Cache {
} }
/** /**
* {@inheritDoc} * {@inheritDoc} This implementation simply returns the RedisTemplate used for configuring the cache, giving access to
* * the underlying Redis store.
* This implementation simply returns the RedisTemplate used for configuring the cache, giving access
* to the underlying Redis store.
*/ */
public Object getNativeCache() { public Object getNativeCache() {
return template; return template;
@@ -96,14 +92,14 @@ class RedisCache implements Cache {
} }
}, true); }, true);
} }
/** /**
* Return the value to which this cache maps the specified key, generically specifying a type that return value will be cast to. * Return the value to which this cache maps the specified key, generically specifying a type that return value will
* be cast to.
* *
* @param key * @param key
* @param type * @param type
* @return * @return
*
* @see DATAREDIS-243 * @see DATAREDIS-243
*/ */
public <T> T get(Object key, Class<T> type) { public <T> T get(Object key, Class<T> type) {
@@ -112,7 +108,6 @@ class RedisCache implements Cache {
return wrapper == null ? null : (T) wrapper.get(); return wrapper == null ? null : (T) wrapper.get();
} }
public void put(final Object key, final Object value) { public void put(final Object key, final Object value) {
final byte[] k = computeKey(key); final byte[] k = computeKey(key);
@@ -121,8 +116,8 @@ class RedisCache implements Cache {
waitForLock(connection); waitForLock(connection);
connection.multi(); connection.multi();
byte[] v; byte[] v;
if(template.getValueSerializer() == null && value instanceof byte[]) { if (template.getValueSerializer() == null && value instanceof byte[]) {
v = (byte[])value; v = (byte[]) value;
} else { } else {
v = template.getValueSerializer().serialize(value); v = template.getValueSerializer().serialize(value);
} }
@@ -141,7 +136,6 @@ class RedisCache implements Cache {
}, true); }, true);
} }
public void evict(Object key) { public void evict(Object key) {
final byte[] k = computeKey(key); final byte[] k = computeKey(key);
@@ -155,7 +149,6 @@ class RedisCache implements Cache {
}, true); }, true);
} }
public void clear() { public void clear() {
// need to del each key individually // need to del each key individually
template.execute(new RedisCallback<Object>() { template.execute(new RedisCallback<Object>() {
@@ -173,8 +166,7 @@ class RedisCache implements Cache {
do { do {
// need to paginate the keys // need to paginate the keys
Set<byte[]> keys = connection.zRange(setName, (offset) * PAGE_SIZE, (offset + 1) * PAGE_SIZE Set<byte[]> keys = connection.zRange(setName, (offset) * PAGE_SIZE, (offset + 1) * PAGE_SIZE - 1);
- 1);
finished = keys.size() < PAGE_SIZE; finished = keys.size() < PAGE_SIZE;
offset++; offset++;
if (!keys.isEmpty()) { if (!keys.isEmpty()) {
@@ -193,8 +185,8 @@ class RedisCache implements Cache {
} }
private byte[] computeKey(Object key) { private byte[] computeKey(Object key) {
if(template.getKeySerializer() == null && key instanceof byte[]) { if (template.getKeySerializer() == null && key instanceof byte[]) {
return (byte[])key; return (byte[]) key;
} }
byte[] k = template.getKeySerializer().serialize(key); byte[] k = template.getKeySerializer().serialize(key);
@@ -223,4 +215,4 @@ class RedisCache implements Cache {
} while (retry); } while (retry);
return foundLock; return foundLock;
} }
} }

View File

@@ -27,10 +27,9 @@ import org.springframework.cache.CacheManager;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
/** /**
* CacheManager implementation for Redis. * CacheManager implementation for Redis. By default saves the keys directly, without appending a prefix (which acts as
* By default saves the keys directly, without appending a prefix (which acts as a namespace). * a namespace). To avoid clashes, it is recommended to change this (by setting 'usePrefix' to 'true'). For performance
* To avoid clashes, it is recommended to change this (by setting 'usePrefix' to 'true'). * reasons, the current implementation uses a set for the keys in each cache.
* For performance reasons, the current implementation uses a set for the keys in each cache.
* *
* @author Costin Leau * @author Costin Leau
*/ */
@@ -81,7 +80,7 @@ public class RedisCacheManager implements CacheManager {
/** /**
* Sets the cachePrefix. Defaults to 'DefaultRedisCachePrefix'). * Sets the cachePrefix. Defaults to 'DefaultRedisCachePrefix').
* *
* @param cachePrefix the cachePrefix to set * @param cachePrefix the cachePrefix to set
*/ */
public void setCachePrefix(RedisCachePrefix cachePrefix) { public void setCachePrefix(RedisCachePrefix cachePrefix) {
@@ -90,7 +89,7 @@ public class RedisCacheManager implements CacheManager {
/** /**
* Sets the default expire time (in seconds). * Sets the default expire time (in seconds).
* *
* @param defaultExpireTime time in seconds. * @param defaultExpireTime time in seconds.
*/ */
public void setDefaultExpiration(long defaultExpireTime) { public void setDefaultExpiration(long defaultExpireTime) {
@@ -99,10 +98,10 @@ public class RedisCacheManager implements CacheManager {
/** /**
* Sets the expire time (in seconds) for cache regions (by key). * Sets the expire time (in seconds) for cache regions (by key).
* *
* @param expires time in seconds * @param expires time in seconds
*/ */
public void setExpires(Map<String, Long> expires) { public void setExpires(Map<String, Long> expires) {
this.expires = (expires != null ? new ConcurrentHashMap<String, Long>(expires) : null); this.expires = (expires != null ? new ConcurrentHashMap<String, Long>(expires) : null);
} }
} }

View File

@@ -17,17 +17,17 @@
package org.springframework.data.redis.cache; package org.springframework.data.redis.cache;
/** /**
* Contract for generating 'prefixes' for Cache keys saved in Redis. * Contract for generating 'prefixes' for Cache keys saved in Redis. Due to the 'flat' nature of the Redis storage, the
* Due to the 'flat' nature of the Redis storage, the prefix is used as a 'namespace' for grouping the key/values inside a cache (and * prefix is used as a 'namespace' for grouping the key/values inside a cache (and to avoid collision with other caches
* to avoid collision with other caches or keys inside Redis). * or keys inside Redis).
* *
* @author Costin Leau * @author Costin Leau
*/ */
public interface RedisCachePrefix { public interface RedisCachePrefix {
/** /**
* Returns the prefix for the given cache (identified by name). * Returns the prefix for the given cache (identified by name). Note the prefix is returned in raw form so it can be
* Note the prefix is returned in raw form so it can be saved directly to Redis without any serialization. * saved directly to Redis without any serialization.
* *
* @param cacheName the name of the cache using the prefix * @param cacheName the name of the cache using the prefix
* @return the prefix for the given cache. * @return the prefix for the given cache.

View File

@@ -28,12 +28,10 @@ import org.w3c.dom.Element;
*/ */
class RedisCollectionParser extends AbstractSimpleBeanDefinitionParser { class RedisCollectionParser extends AbstractSimpleBeanDefinitionParser {
protected Class<?> getBeanClass(Element element) { protected Class<?> getBeanClass(Element element) {
return RedisCollectionFactoryBean.class; return RedisCollectionFactoryBean.class;
} }
protected void postProcess(BeanDefinitionBuilder beanDefinition, Element element) { protected void postProcess(BeanDefinitionBuilder beanDefinition, Element element) {
String template = element.getAttribute("template"); String template = element.getAttribute("template");
if (StringUtils.hasText(template)) { if (StringUtils.hasText(template)) {
@@ -41,7 +39,6 @@ class RedisCollectionParser extends AbstractSimpleBeanDefinitionParser {
} }
} }
protected boolean isEligibleAttribute(String attributeName) { protected boolean isEligibleAttribute(String attributeName) {
return super.isEligibleAttribute(attributeName) && (!"template".equals(attributeName)); return super.isEligibleAttribute(attributeName) && (!"template".equals(attributeName));
} }

View File

@@ -43,17 +43,15 @@ import org.w3c.dom.NamedNodeMap;
*/ */
class RedisListenerContainerParser extends AbstractSimpleBeanDefinitionParser { class RedisListenerContainerParser extends AbstractSimpleBeanDefinitionParser {
protected Class<RedisMessageListenerContainer> getBeanClass(Element element) { protected Class<RedisMessageListenerContainer> getBeanClass(Element element) {
return RedisMessageListenerContainer.class; return RedisMessageListenerContainer.class;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
// parse attributes (but replace the value assignment with references) // parse attributes (but replace the value assignment with references)
NamedNodeMap attributes = element.getAttributes(); NamedNodeMap attributes = element.getAttributes();
for (int x = 0; x < attributes.getLength(); x++) { for (int x = 0; x < attributes.getLength(); x++) {
Attr attribute = (Attr) attributes.item(x); Attr attribute = (Attr) attributes.item(x);
if (isEligibleAttribute(attribute, parserContext)) { if (isEligibleAttribute(attribute, parserContext)) {
@@ -87,13 +85,13 @@ class RedisListenerContainerParser extends AbstractSimpleBeanDefinitionParser {
} }
} }
protected boolean isEligibleAttribute(String attributeName) { protected boolean isEligibleAttribute(String attributeName) {
return (!"phase".equals(attributeName)); return (!"phase".equals(attributeName));
} }
/** /**
* Parses a listener definition. Returns the listener bean reference definition (as the array first entry) and its associated topics (also as bean definitions). * Parses a listener definition. Returns the listener bean reference definition (as the array first entry) and its
* associated topics (also as bean definitions).
* *
* @param element * @param element
* @return * @return
@@ -103,17 +101,17 @@ class RedisListenerContainerParser extends AbstractSimpleBeanDefinitionParser {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MessageListenerAdapter.class); BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MessageListenerAdapter.class);
builder.addConstructorArgReference(element.getAttribute("ref")); builder.addConstructorArgReference(element.getAttribute("ref"));
String method = element.getAttribute("method"); String method = element.getAttribute("method");
if (StringUtils.hasText(method)){ if (StringUtils.hasText(method)) {
builder.addPropertyValue("defaultListenerMethod", method); builder.addPropertyValue("defaultListenerMethod", method);
} }
String serializer = element.getAttribute("serializer"); String serializer = element.getAttribute("serializer");
if (StringUtils.hasText(serializer)){ if (StringUtils.hasText(serializer)) {
builder.addPropertyReference("serializer", serializer); builder.addPropertyReference("serializer", serializer);
} }
// assemble topics // assemble topics
Collection<Topic> topics = new ArrayList<Topic>(); Collection<Topic> topics = new ArrayList<Topic>();
@@ -132,8 +130,7 @@ class RedisListenerContainerParser extends AbstractSimpleBeanDefinitionParser {
return ret; return ret;
} }
protected boolean shouldGenerateId() { protected boolean shouldGenerateId() {
return true; return true;
} }
} }

View File

@@ -25,7 +25,6 @@ import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
*/ */
class RedisNamespaceHandler extends NamespaceHandlerSupport { class RedisNamespaceHandler extends NamespaceHandlerSupport {
public void init() { public void init() {
registerBeanDefinitionParser("listener-container", new RedisListenerContainerParser()); registerBeanDefinitionParser("listener-container", new RedisListenerContainerParser());
registerBeanDefinitionParser("collection", new RedisCollectionParser()); registerBeanDefinitionParser("collection", new RedisCollectionParser());

View File

@@ -22,10 +22,9 @@ import org.springframework.data.redis.connection.srp.SrpConnectionFactory;
/** /**
* Utilities for examining a {@link RedisConnection} * Utilities for examining a {@link RedisConnection}
* *
* @author Jennifer Hickey * @author Jennifer Hickey
* @author Thomas Darimont * @author Thomas Darimont
*
*/ */
public abstract class ConnectionUtils { public abstract class ConnectionUtils {

View File

@@ -15,7 +15,6 @@
*/ */
package org.springframework.data.redis.connection; package org.springframework.data.redis.connection;
/** /**
* Default message implementation. * Default message implementation.
* *
@@ -32,19 +31,16 @@ public class DefaultMessage implements Message {
this.channel = channel; this.channel = channel;
} }
public byte[] getChannel() { public byte[] getChannel() {
return (channel != null ? channel.clone() : null); return (channel != null ? channel.clone() : null);
} }
public byte[] getBody() { public byte[] getBody() {
return (body != null ? body.clone() : null); return (body != null ? body.clone() : null);
} }
public String toString() { public String toString() {
if (toString == null){ if (toString == null) {
toString = new String(body); toString = new String(body);
} }
return toString; return toString;

View File

@@ -18,7 +18,6 @@ package org.springframework.data.redis.connection;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
* Default implementation for {@link SortParameters}. * Default implementation for {@link SortParameters}.
* *
@@ -41,7 +40,7 @@ public class DefaultSortParameters implements SortParameters {
/** /**
* Constructs a new <code>DefaultSortParameters</code> instance. * Constructs a new <code>DefaultSortParameters</code> instance.
* *
* @param limit * @param limit
* @param order * @param order
* @param alphabetic * @param alphabetic
@@ -52,7 +51,7 @@ public class DefaultSortParameters implements SortParameters {
/** /**
* Constructs a new <code>DefaultSortParameters</code> instance. * Constructs a new <code>DefaultSortParameters</code> instance.
* *
* @param byPattern * @param byPattern
* @param limit * @param limit
* @param getPattern * @param getPattern
@@ -68,7 +67,6 @@ public class DefaultSortParameters implements SortParameters {
setGetPattern(getPattern); setGetPattern(getPattern);
} }
public byte[] getByPattern() { public byte[] getByPattern() {
return byPattern; return byPattern;
} }
@@ -77,7 +75,6 @@ public class DefaultSortParameters implements SortParameters {
this.byPattern = byPattern; this.byPattern = byPattern;
} }
public Range getLimit() { public Range getLimit() {
return limit; return limit;
} }
@@ -86,7 +83,6 @@ public class DefaultSortParameters implements SortParameters {
this.limit = limit; this.limit = limit;
} }
public byte[][] getGetPattern() { public byte[][] getGetPattern() {
return getPattern.toArray(new byte[getPattern.size()][]); return getPattern.toArray(new byte[getPattern.size()][]);
} }
@@ -98,7 +94,7 @@ public class DefaultSortParameters implements SortParameters {
public void setGetPattern(byte[][] gPattern) { public void setGetPattern(byte[][] gPattern) {
getPattern.clear(); getPattern.clear();
if(gPattern == null) { if (gPattern == null) {
return; return;
} }
@@ -107,7 +103,6 @@ public class DefaultSortParameters implements SortParameters {
} }
} }
public Order getOrder() { public Order getOrder() {
return order; return order;
} }
@@ -116,7 +111,6 @@ public class DefaultSortParameters implements SortParameters {
this.order = order; this.order = order;
} }
public Boolean isAlphabetic() { public Boolean isAlphabetic() {
return alphabetic; return alphabetic;
} }
@@ -168,4 +162,4 @@ public class DefaultSortParameters implements SortParameters {
setLimit(new Range(start, count)); setLimit(new Range(start, count));
return this; return this;
} }
} }

View File

@@ -20,7 +20,7 @@ import org.springframework.data.redis.connection.StringRedisConnection.StringTup
/** /**
* Default implementation for {@link StringTuple} interface. * Default implementation for {@link StringTuple} interface.
* *
* @author Costin Leau * @author Costin Leau
*/ */
public class DefaultStringTuple extends DefaultTuple implements StringTuple { public class DefaultStringTuple extends DefaultTuple implements StringTuple {
@@ -29,7 +29,7 @@ public class DefaultStringTuple extends DefaultTuple implements StringTuple {
/** /**
* Constructs a new <code>DefaultStringTuple</code> instance. * Constructs a new <code>DefaultStringTuple</code> instance.
* *
* @param value * @param value
* @param score * @param score
*/ */
@@ -41,7 +41,7 @@ public class DefaultStringTuple extends DefaultTuple implements StringTuple {
/** /**
* Constructs a new <code>DefaultStringTuple</code> instance. * Constructs a new <code>DefaultStringTuple</code> instance.
* *
* @param tuple * @param tuple
* @param valueAsString * @param valueAsString
*/ */
@@ -50,12 +50,10 @@ public class DefaultStringTuple extends DefaultTuple implements StringTuple {
this.valueAsString = valueAsString; this.valueAsString = valueAsString;
} }
public String getValueAsString() { public String getValueAsString() {
return valueAsString; return valueAsString;
} }
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = super.hashCode(); int result = super.hashCode();
@@ -63,7 +61,6 @@ public class DefaultStringTuple extends DefaultTuple implements StringTuple {
return result; return result;
} }
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (super.equals(obj)) { if (super.equals(obj)) {
if (!(obj instanceof DefaultStringTuple)) if (!(obj instanceof DefaultStringTuple))
@@ -72,8 +69,7 @@ public class DefaultStringTuple extends DefaultTuple implements StringTuple {
if (valueAsString == null) { if (valueAsString == null) {
if (other.valueAsString != null) if (other.valueAsString != null)
return false; return false;
} } else if (!valueAsString.equals(other.valueAsString))
else if (!valueAsString.equals(other.valueAsString))
return false; return false;
return true; return true;
} }
@@ -83,4 +79,4 @@ public class DefaultStringTuple extends DefaultTuple implements StringTuple {
public String toString() { public String toString() {
return "DefaultStringTuple[value=" + getValueAsString() + ", score=" + getScore() + "]"; return "DefaultStringTuple[value=" + getValueAsString() + ", score=" + getScore() + "]";
} }
} }

View File

@@ -29,10 +29,9 @@ public class DefaultTuple implements Tuple {
private final Double score; private final Double score;
private final byte[] value; private final byte[] value;
/** /**
* Constructs a new <code>DefaultTuple</code> instance. * Constructs a new <code>DefaultTuple</code> instance.
* *
* @param value * @param value
* @param score * @param score
*/ */
@@ -41,17 +40,14 @@ public class DefaultTuple implements Tuple {
this.value = value; this.value = value;
} }
public Double getScore() { public Double getScore() {
return score; return score;
} }
public byte[] getValue() { public byte[] getValue() {
return value; return value;
} }
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) if (this == obj)
return true; return true;
@@ -63,15 +59,13 @@ public class DefaultTuple implements Tuple {
if (score == null) { if (score == null) {
if (other.score != null) if (other.score != null)
return false; return false;
} } else if (!score.equals(other.score))
else if (!score.equals(other.score))
return false; return false;
if (!Arrays.equals(value, other.value)) if (!Arrays.equals(value, other.value))
return false; return false;
return true; return true;
} }
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
@@ -80,10 +74,9 @@ public class DefaultTuple implements Tuple {
return result; return result;
} }
public int compareTo(Double o) { public int compareTo(Double o) {
Double d = (score == null ? Double.valueOf(0.0d) : score); Double d = (score == null ? Double.valueOf(0.0d) : score);
Double a = (o == null ? Double.valueOf(0.0d) : o); Double a = (o == null ? Double.valueOf(0.0d) : o);
return d.compareTo(a); return d.compareTo(a);
} }
} }

View File

@@ -19,11 +19,9 @@ import org.springframework.core.convert.converter.Converter;
/** /**
* The result of an asynchronous operation * The result of an asynchronous operation
* *
* @author Jennifer Hickey * @author Jennifer Hickey
* * @param <T> The data type of the object that holds the future result (usually of type Future)
* @param <T>
* The data type of the object that holds the future result (usually of type Future)
*/ */
abstract public class FutureResult<T> { abstract public class FutureResult<T> {
@@ -31,8 +29,7 @@ abstract public class FutureResult<T> {
protected boolean status = false; protected boolean status = false;
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes") protected Converter converter;
protected Converter converter;
public FutureResult(T resultHolder) { public FutureResult(T resultHolder) {
this.resultHolder = resultHolder; this.resultHolder = resultHolder;
@@ -50,9 +47,8 @@ abstract public class FutureResult<T> {
/** /**
* Converts the given result if a converter is specified, else returns the result * Converts the given result if a converter is specified, else returns the result
* *
* @param result * @param result The result to convert
* The result to convert
* @return The converted result * @return The converted result
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@@ -69,9 +65,8 @@ abstract public class FutureResult<T> {
} }
/** /**
* Indicates if this result is the status of an operation. Typically status results will be * Indicates if this result is the status of an operation. Typically status results will be discarded on conversion.
* discarded on conversion. *
*
* @return true if this is a status result (i.e. OK) * @return true if this is a status result (i.e. OK)
*/ */
public boolean isStatus() { public boolean isStatus() {
@@ -79,9 +74,8 @@ abstract public class FutureResult<T> {
} }
/** /**
* Indicates if this result is the status of an operation. Typically status results will be * Indicates if this result is the status of an operation. Typically status results will be discarded on conversion.
* discarded on conversion. *
*
* @return true if this is a status result (i.e. OK) * @return true if this is a status result (i.e. OK)
*/ */
public void setStatus(boolean status) { public void setStatus(boolean status) {

View File

@@ -26,11 +26,11 @@ public interface Message extends Serializable {
/** /**
* Returns the body (or the payload) of the message. * Returns the body (or the payload) of the message.
* *
* @return message body * @return message body
*/ */
byte[] getBody(); byte[] getBody();
/** /**
* Returns the channel associated with the message. * Returns the channel associated with the message.
* *

View File

@@ -15,32 +15,25 @@
*/ */
package org.springframework.data.redis.connection; package org.springframework.data.redis.connection;
/** /**
* Pool of resources * Pool of resources
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
public interface Pool<T> { public interface Pool<T> {
/** /**
*
* @return A resource, if available * @return A resource, if available
*/ */
T getResource(); T getResource();
/** /**
* * @param resource A broken resource that should be invalidated
* @param resource
* A broken resource that should be invalidated
*/ */
void returnBrokenResource(final T resource); void returnBrokenResource(final T resource);
/** /**
* * @param resource A resource to return to the pool
* @param resource
* A resource to return to the pool
*/ */
void returnResource(final T resource); void returnResource(final T resource);

View File

@@ -21,7 +21,6 @@ import org.springframework.core.NestedRuntimeException;
* Exception thrown when there are issues with a resource pool * Exception thrown when there are issues with a resource pool
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class PoolException extends NestedRuntimeException { public class PoolException extends NestedRuntimeException {

View File

@@ -16,7 +16,6 @@
package org.springframework.data.redis.connection; package org.springframework.data.redis.connection;
/** /**
* Interface for the commands supported by Redis. * Interface for the commands supported by Redis.
* *
@@ -26,15 +25,14 @@ public interface RedisCommands extends RedisKeyCommands, RedisStringCommands, Re
RedisZSetCommands, RedisHashCommands, RedisTxCommands, RedisPubSubCommands, RedisConnectionCommands, RedisZSetCommands, RedisHashCommands, RedisTxCommands, RedisPubSubCommands, RedisConnectionCommands,
RedisServerCommands, RedisScriptingCommands { RedisServerCommands, RedisScriptingCommands {
/** /**
* 'Native' or 'raw' execution of the given command along-side the given arguments. * 'Native' or 'raw' execution of the given command along-side the given arguments. The command is executed as is,
* The command is executed as is, with as little 'interpretation' as possible - it is up to the caller * with as little 'interpretation' as possible - it is up to the caller to take care of any processing of arguments or
* to take care of any processing of arguments or the result. * the result.
* *
* @param command Command to execute * @param command Command to execute
* @param args Possible command arguments (may be null) * @param args Possible command arguments (may be null)
* @return execution result. * @return execution result.
*/ */
Object execute(String command, byte[]... args); Object execute(String command, byte[]... args);
} }

View File

@@ -21,10 +21,8 @@ import java.util.List;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
/** /**
* A connection to a Redis server. Acts as an common abstraction across various * A connection to a Redis server. Acts as an common abstraction across various Redis client libraries (or drivers).
* Redis client libraries (or drivers). Additionally performs exception translation * Additionally performs exception translation between the underlying Redis client library and Spring DAO exceptions.
* between the underlying Redis client library and Spring DAO exceptions.
*
* The methods follow as much as possible the Redis names and conventions. * The methods follow as much as possible the Redis names and conventions.
* *
* @author Costin Leau * @author Costin Leau
@@ -33,7 +31,7 @@ public interface RedisConnection extends RedisCommands {
/** /**
* Closes (or quits) the connection. * Closes (or quits) the connection.
* *
* @throws DataAccessException * @throws DataAccessException
*/ */
void close() throws DataAccessException; void close() throws DataAccessException;
@@ -53,11 +51,9 @@ public interface RedisConnection extends RedisCommands {
Object getNativeConnection(); Object getNativeConnection();
/** /**
* Indicates whether the connection is in "queue"(or "MULTI") mode or not. * Indicates whether the connection is in "queue"(or "MULTI") mode or not. When queueing, all commands are postponed
* When queueing, all commands are postponed until EXEC or DISCARD commands * until EXEC or DISCARD commands are issued. Since in queueing no results are returned, the connection will return
* are issued. * NULL on all operations that interact with the data.
* Since in queueing no results are returned, the connection will return NULL
* on all operations that interact with the data.
* *
* @return true if the connection is in queue/MULTI mode, false otherwise * @return true if the connection is in queue/MULTI mode, false otherwise
*/ */
@@ -65,7 +61,7 @@ public interface RedisConnection extends RedisCommands {
/** /**
* Indicates whether the connection is currently pipelined or not. * Indicates whether the connection is currently pipelined or not.
* *
* @return true if the connection is pipelined, false otherwise * @return true if the connection is pipelined, false otherwise
* @see #openPipeline() * @see #openPipeline()
* @see #isQueueing() * @see #isQueueing()
@@ -73,28 +69,27 @@ public interface RedisConnection extends RedisCommands {
boolean isPipelined(); boolean isPipelined();
/** /**
* Activates the pipeline mode for this connection. When pipelined, all commands return null * Activates the pipeline mode for this connection. When pipelined, all commands return null (the reply is read at the
* (the reply is read at the end through {@link #closePipeline()}. * end through {@link #closePipeline()}. Calling this method when the connection is already pipelined has no effect.
* Calling this method when the connection is already pipelined has no effect. * Pipelining is used for issuing commands without requesting the response right away but rather at the end of the
* * batch. While somewhat similar to MULTI, pipelining does not guarantee atomicity - it only tries to improve
* Pipelining is used for issuing commands without requesting the response right away but rather * performance when issuing a lot of commands (such as in batching scenarios).
* at the end of the batch. While somewhat similar to MULTI, pipelining does not * <p>
* guarantee atomicity - it only tries to improve performance when issuing a lot of * Note:
* commands (such as in batching scenarios). * </p>
* * Consider doing some performance testing before using this feature since in many cases the performance benefits are
* <p>Note:</p>Consider doing some performance testing before using this feature since * minimal yet the impact on usage are not.
* in many cases the performance benefits are minimal yet the impact on usage are not.
* *
* @see #multi() * @see #multi()
*/ */
void openPipeline(); void openPipeline();
/** /**
* Executes the commands in the pipeline and returns their result. * Executes the commands in the pipeline and returns their result. If the connection is not pipelined, an empty
* If the connection is not pipelined, an empty collection is returned. * collection is returned.
* *
* @throws RedisPipelineException if the pipeline contains any incorrect/invalid statements * @throws RedisPipelineException if the pipeline contains any incorrect/invalid statements
* @return the result of the executed commands. * @return the result of the executed commands.
*/ */
List<Object> closePipeline() throws RedisPipelineException; List<Object> closePipeline() throws RedisPipelineException;
} }

View File

@@ -15,7 +15,6 @@
*/ */
package org.springframework.data.redis.connection; package org.springframework.data.redis.connection;
/** /**
* Connection-specific commands supported by Redis. * Connection-specific commands supported by Redis.
* *
@@ -28,4 +27,4 @@ public interface RedisConnectionCommands {
byte[] echo(byte[] message); byte[] echo(byte[] message);
String ping(); String ping();
} }

View File

@@ -33,14 +33,11 @@ public interface RedisConnectionFactory extends PersistenceExceptionTranslator {
RedisConnection getConnection(); RedisConnection getConnection();
/** /**
* Specifies if pipelined results should be converted to the expected data * Specifies if pipelined results should be converted to the expected data type. If false, results of
* type. If false, results of {@link RedisConnection#closePipeline()} and {RedisConnection#exec()} * {@link RedisConnection#closePipeline()} and {RedisConnection#exec()} will be of the type returned by the underlying
* will be of the type returned by the underlying driver * driver This method is mostly for backwards compatibility with 1.0. It is generally always a good idea to allow
* * results to be converted and deserialized. In fact, this is now the default behavior.
* This method is mostly for backwards compatibility with 1.0. It is generally *
* always a good idea to allow results to be converted and deserialized.
* In fact, this is now the default behavior.
*
* @return Whether or not to convert pipeline and tx results * @return Whether or not to convert pipeline and tx results
*/ */
boolean getConvertPipelineAndTxResults(); boolean getConvertPipelineAndTxResults();

View File

@@ -26,7 +26,7 @@ public class RedisInvalidSubscriptionException extends InvalidDataAccessResource
/** /**
* Constructs a new <code>RedisInvalidSubscriptionException</code> instance. * Constructs a new <code>RedisInvalidSubscriptionException</code> instance.
* *
* @param msg * @param msg
* @param cause * @param cause
*/ */
@@ -36,7 +36,7 @@ public class RedisInvalidSubscriptionException extends InvalidDataAccessResource
/** /**
* Constructs a new <code>RedisInvalidSubscriptionException</code> instance. * Constructs a new <code>RedisInvalidSubscriptionException</code> instance.
* *
* @param msg * @param msg
*/ */
public RedisInvalidSubscriptionException(String msg) { public RedisInvalidSubscriptionException(String msg) {

View File

@@ -18,7 +18,6 @@ package org.springframework.data.redis.connection;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
/** /**
* Key-specific commands supported by Redis. * Key-specific commands supported by Redis.
* *
@@ -64,4 +63,4 @@ public interface RedisKeyCommands {
byte[] dump(byte[] key); byte[] dump(byte[] key);
void restore(byte[] key, long ttlInMillis, byte[] serializedValue); void restore(byte[] key, long ttlInMillis, byte[] serializedValue);
} }

View File

@@ -26,14 +26,14 @@ import java.util.List;
public interface RedisListCommands { public interface RedisListCommands {
/** /**
* List insertion position. * List insertion position.
*/ */
public enum Position { public enum Position {
BEFORE, AFTER BEFORE, AFTER
} }
Long rPush(byte[] key, byte[]... values); Long rPush(byte[] key, byte[]... values);
Long lPush(byte[] key, byte[]... value); Long lPush(byte[] key, byte[]... value);
Long rPushX(byte[] key, byte[] value); Long rPushX(byte[] key, byte[] value);

View File

@@ -22,11 +22,11 @@ import java.util.List;
import org.springframework.dao.InvalidDataAccessResourceUsageException; import org.springframework.dao.InvalidDataAccessResourceUsageException;
/** /**
* Exception thrown when executing/closing a pipeline that contains one or multiple invalid/incorrect statements. * Exception thrown when executing/closing a pipeline that contains one or multiple invalid/incorrect statements. The
* The exception might also contain the pipeline result (if the driver returns it), allowing for analysis and tracing. * exception might also contain the pipeline result (if the driver returns it), allowing for analysis and tracing.
* <p/> * <p/>
* Typically, the first exception returned by the pipeline is used as the <i>cause</i> of this exception for easier * Typically, the first exception returned by the pipeline is used as the <i>cause</i> of this exception for easier
* debugging. * debugging.
* *
* @author Costin Leau * @author Costin Leau
*/ */
@@ -36,7 +36,7 @@ public class RedisPipelineException extends InvalidDataAccessResourceUsageExcept
/** /**
* Constructs a new <code>RedisPipelineException</code> instance. * Constructs a new <code>RedisPipelineException</code> instance.
* *
* @param msg the message * @param msg the message
* @param cause the cause * @param cause the cause
* @param pipelineResult the pipeline result * @param pipelineResult the pipeline result
@@ -48,7 +48,7 @@ public class RedisPipelineException extends InvalidDataAccessResourceUsageExcept
/** /**
* Constructs a new <code>RedisPipelineException</code> instance using a default message. * Constructs a new <code>RedisPipelineException</code> instance using a default message.
* *
* @param cause the cause * @param cause the cause
* @param pipelineResult the pipeline result * @param pipelineResult the pipeline result
*/ */
@@ -57,9 +57,9 @@ public class RedisPipelineException extends InvalidDataAccessResourceUsageExcept
} }
/** /**
* Constructs a new <code>RedisPipelineException</code> instance using a default message * Constructs a new <code>RedisPipelineException</code> instance using a default message and an empty pipeline result
* and an empty pipeline result list. * list.
* *
* @param cause the cause * @param cause the cause
*/ */
public RedisPipelineException(Exception cause) { public RedisPipelineException(Exception cause) {
@@ -78,13 +78,12 @@ public class RedisPipelineException extends InvalidDataAccessResourceUsageExcept
} }
/** /**
* Optionally returns the result of the pipeline that caused the exception. * Optionally returns the result of the pipeline that caused the exception. Typically contains both the results of the
* Typically contains both the results of the successful statements but also * successful statements but also the exceptions of the incorrect ones.
* the exceptions of the incorrect ones.
* *
* @return result of the pipeline * @return result of the pipeline
*/ */
public List<Object> getPipelineResult() { public List<Object> getPipelineResult() {
return results; return results;
} }
} }

View File

@@ -23,16 +23,14 @@ package org.springframework.data.redis.connection;
public interface RedisPubSubCommands { public interface RedisPubSubCommands {
/** /**
* Indicates whether the current connection is subscribed (to at least one channel) * Indicates whether the current connection is subscribed (to at least one channel) or not.
* or not.
* *
* @return true if the connection is subscribed, false otherwise * @return true if the connection is subscribed, false otherwise
*/ */
boolean isSubscribed(); boolean isSubscribed();
/** /**
* Returns the current subscription for this connection or null if the connection is * Returns the current subscription for this connection or null if the connection is not subscribed.
* not subscribed.
* *
* @return the current subscription, null if none is available * @return the current subscription, null if none is available
*/ */
@@ -48,13 +46,10 @@ public interface RedisPubSubCommands {
Long publish(byte[] channel, byte[] message); Long publish(byte[] channel, byte[] message);
/** /**
* Subscribes the connection to the given channels. * Subscribes the connection to the given channels. Once subscribed, a connection enters listening mode and can only
* Once subscribed, a connection * subscribe to other channels or unsubscribe. No other commands are accepted until the connection is unsubscribed.
* enters listening mode and can only subscribe to other channels or unsubscribe.
* No other commands are accepted until the connection is unsubscribed.
* <p/> * <p/>
* Note that this operation is blocking and the current thread starts waiting * Note that this operation is blocking and the current thread starts waiting for new messages immediately.
* for new messages immediately.
* *
* @param listener message listener * @param listener message listener
* @param channels channel names * @param channels channel names
@@ -62,16 +57,14 @@ public interface RedisPubSubCommands {
void subscribe(MessageListener listener, byte[]... channels); void subscribe(MessageListener listener, byte[]... channels);
/** /**
* Subscribes the connection to all channels matching the given patterns. * Subscribes the connection to all channels matching the given patterns. Once subscribed, a connection enters
* Once subscribed, a connection * listening mode and can only subscribe to other channels or unsubscribe. No other commands are accepted until the
* enters listening mode and can only subscribe to other channels or unsubscribe. * connection is unsubscribed.
* No other commands are accepted until the connection is unsubscribed.
* <p/> * <p/>
* Note that this operation is blocking and the current thread starts waiting * Note that this operation is blocking and the current thread starts waiting for new messages immediately.
* for new messages immediately.
* *
* @param listener message listener * @param listener message listener
* @param patterns channel name patterns * @param patterns channel name patterns
*/ */
void pSubscribe(MessageListener listener, byte[]... patterns); void pSubscribe(MessageListener listener, byte[]... patterns);
} }

View File

@@ -25,15 +25,15 @@ import java.util.List;
*/ */
public interface RedisScriptingCommands { public interface RedisScriptingCommands {
void scriptFlush(); void scriptFlush();
void scriptKill(); void scriptKill();
String scriptLoad(byte[] script); String scriptLoad(byte[] script);
List<Boolean> scriptExists(String... scriptSha1); List<Boolean> scriptExists(String... scriptSha1);
<T> T eval(byte[] script, ReturnType returnType, int numKeys, byte[]... keysAndArgs); <T> T eval(byte[] script, ReturnType returnType, int numKeys, byte[]... keysAndArgs);
<T> T evalSha(String scriptSha1, ReturnType returnType, int numKeys, byte[]... keysAndArgs); <T> T evalSha(String scriptSha1, ReturnType returnType, int numKeys, byte[]... keysAndArgs);
} }

View File

@@ -18,8 +18,7 @@ package org.springframework.data.redis.connection;
import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.dao.InvalidDataAccessApiUsageException;
/** /**
* Exception thrown when issuing commands on a connection that is subscribed and waiting * Exception thrown when issuing commands on a connection that is subscribed and waiting for events.
* for events.
* *
* @author Costin Leau * @author Costin Leau
* @see org.springframework.data.redis.connection.RedisPubSubCommands * @see org.springframework.data.redis.connection.RedisPubSubCommands
@@ -28,7 +27,7 @@ public class RedisSubscribedConnectionException extends InvalidDataAccessApiUsag
/** /**
* Constructs a new <code>RedisSubscribedConnectionException</code> instance. * Constructs a new <code>RedisSubscribedConnectionException</code> instance.
* *
* @param msg * @param msg
* @param cause * @param cause
*/ */
@@ -38,7 +37,7 @@ public class RedisSubscribedConnectionException extends InvalidDataAccessApiUsag
/** /**
* Constructs a new <code>RedisSubscribedConnectionException</code> instance. * Constructs a new <code>RedisSubscribedConnectionException</code> instance.
* *
* @param msg * @param msg
*/ */
public RedisSubscribedConnectionException(String msg) { public RedisSubscribedConnectionException(String msg) {

View File

@@ -17,7 +17,6 @@ package org.springframework.data.redis.connection;
import java.util.List; import java.util.List;
/** /**
* Transaction/Batch specific commands supported by Redis. * Transaction/Batch specific commands supported by Redis.
* *

View File

@@ -18,7 +18,6 @@ package org.springframework.data.redis.connection;
import java.util.Set; import java.util.Set;
/** /**
* ZSet(SortedSet)-specific commands supported by Redis. * ZSet(SortedSet)-specific commands supported by Redis.
* *
@@ -27,14 +26,14 @@ import java.util.Set;
public interface RedisZSetCommands { public interface RedisZSetCommands {
/** /**
* Sort aggregation operations. * Sort aggregation operations.
*/ */
public enum Aggregate { public enum Aggregate {
SUM, MIN, MAX; SUM, MIN, MAX;
} }
/** /**
* ZSet tuple. * ZSet tuple.
*/ */
public interface Tuple extends Comparable<Double> { public interface Tuple extends Comparable<Double> {
byte[] getValue(); byte[] getValue();
@@ -95,4 +94,4 @@ public interface RedisZSetCommands {
Long zInterStore(byte[] destKey, byte[]... sets); Long zInterStore(byte[] destKey, byte[]... sets);
Long zInterStore(byte[] destKey, Aggregate aggregate, int[] weights, byte[]... sets); Long zInterStore(byte[] destKey, Aggregate aggregate, int[] weights, byte[]... sets);
} }

View File

@@ -18,11 +18,10 @@ package org.springframework.data.redis.connection;
import java.util.List; import java.util.List;
/** /**
* Represents a data type returned from Redis, currently used to denote the * Represents a data type returned from Redis, currently used to denote the expected return type of Redis scripting
* expected return type of Redis scripting commands * commands
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
public enum ReturnType { public enum ReturnType {
@@ -42,16 +41,16 @@ public enum ReturnType {
VALUE; VALUE;
public static ReturnType fromJavaType(Class<?> javaType) { public static ReturnType fromJavaType(Class<?> javaType) {
if(javaType == null) { if (javaType == null) {
return ReturnType.STATUS; return ReturnType.STATUS;
} }
if(javaType.isAssignableFrom(List.class)) { if (javaType.isAssignableFrom(List.class)) {
return ReturnType.MULTI; return ReturnType.MULTI;
} }
if(javaType.isAssignableFrom(Boolean.class)) { if (javaType.isAssignableFrom(Boolean.class)) {
return ReturnType.BOOLEAN; return ReturnType.BOOLEAN;
} }
if(javaType.isAssignableFrom(Long.class)) { if (javaType.isAssignableFrom(Long.class)) {
return ReturnType.INTEGER; return ReturnType.INTEGER;
} }
return ReturnType.VALUE; return ReturnType.VALUE;

View File

@@ -31,7 +31,6 @@ public interface SortParameters {
/** /**
* Utility class wrapping the 'LIMIT' setting. * Utility class wrapping the 'LIMIT' setting.
*
*/ */
static class Range { static class Range {
private final long start; private final long start;
@@ -59,34 +58,31 @@ public interface SortParameters {
Order getOrder(); Order getOrder();
/** /**
* Indicates if the sorting is numeric (default) or alphabetical (lexicographical). * Indicates if the sorting is numeric (default) or alphabetical (lexicographical). Can be null if nothing is
* Can be null if nothing is specified. * specified.
* *
* @return the type of sorting * @return the type of sorting
*/ */
Boolean isAlphabetic(); Boolean isAlphabetic();
/** /**
* Returns the pattern (if set) for sorting by external keys (<tt>BY</tt>). * Returns the pattern (if set) for sorting by external keys (<tt>BY</tt>). Can be null if nothing is specified.
* Can be null if nothing is specified. *
*
* @return <tt>BY</tt> pattern. * @return <tt>BY</tt> pattern.
*/ */
byte[] getByPattern(); byte[] getByPattern();
/** /**
* Returns the pattern (if set) for retrieving external keys (<tt>GET</tt>). * Returns the pattern (if set) for retrieving external keys (<tt>GET</tt>). Can be null if nothing is specified.
* Can be null if nothing is specified.
* *
* @return <tt>GET</tt> pattern. * @return <tt>GET</tt> pattern.
*/ */
byte[][] getGetPattern(); byte[][] getGetPattern();
/** /**
* Returns the sorting limit (range or pagination). * Returns the sorting limit (range or pagination). Can be null if nothing is specified.
* Can be null if nothing is specified.
* *
* @return sorting limit/range * @return sorting limit/range
*/ */
Range getLimit(); Range getLimit();
} }

View File

@@ -25,13 +25,13 @@ import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer;
/** /**
* Convenience extension of {@link RedisConnection} that accepts and returns {@link String}s instead of * Convenience extension of {@link RedisConnection} that accepts and returns {@link String}s instead of byte arrays.
* byte arrays. Uses a {@link RedisSerializer} underneath to perform the conversion. * Uses a {@link RedisSerializer} underneath to perform the conversion.
* *
* @author Costin Leau * @author Costin Leau
* @see RedisCallback * @see RedisCallback
* @see RedisSerializer * @see RedisSerializer
* @see StringRedisTemplate * @see StringRedisTemplate
*/ */
public interface StringRedisConnection extends RedisConnection { public interface StringRedisConnection extends RedisConnection {
@@ -280,4 +280,4 @@ public interface StringRedisConnection extends RedisConnection {
<T> T eval(String script, ReturnType returnType, int numKeys, String... keysAndArgs); <T> T eval(String script, ReturnType returnType, int numKeys, String... keysAndArgs);
<T> T evalSha(String scriptSha1, ReturnType returnType, int numKeys, String... keysAndArgs); <T> T evalSha(String scriptSha1, ReturnType returnType, int numKeys, String... keysAndArgs);
} }

View File

@@ -18,10 +18,8 @@ package org.springframework.data.redis.connection;
import java.util.Collection; import java.util.Collection;
/** /**
* Subscription for Redis channels. Just like the underlying {@link RedisConnection}, * Subscription for Redis channels. Just like the underlying {@link RedisConnection}, it should not be used by multiple
* it should not be used by multiple threads. * threads. Note that once a subscription died, it cannot accept any more subscriptions.
*
* Note that once a subscription died, it cannot accept any more subscriptions.
* *
* @author Costin Leau * @author Costin Leau
*/ */
@@ -60,7 +58,7 @@ public interface Subscription {
/** /**
* Cancels the subscription for all channels matching the given patterns. * Cancels the subscription for all channels matching the given patterns.
* *
* @param patterns * @param patterns
*/ */
void pUnsubscribe(byte[]... patterns); void pUnsubscribe(byte[]... patterns);
@@ -87,10 +85,9 @@ public interface Subscription {
MessageListener getListener(); MessageListener getListener();
/** /**
* Indicates whether this subscription is still 'alive' * Indicates whether this subscription is still 'alive' or not.
* or not.
* *
* @return true if the subscription still applies, false otherwise. * @return true if the subscription still applies, false otherwise.
*/ */
boolean isAlive(); boolean isAlive();
} }

View File

@@ -26,9 +26,8 @@ import org.springframework.data.redis.connection.RedisZSetCommands.Tuple;
/** /**
* Common type converters * Common type converters
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
abstract public class Converters { abstract public class Converters {
@@ -68,7 +67,7 @@ abstract public class Converters {
public static List<Object> toObjects(Set<Tuple> tuples) { public static List<Object> toObjects(Set<Tuple> tuples) {
List<Object> tupleArgs = new ArrayList<Object>(tuples.size() * 2); List<Object> tupleArgs = new ArrayList<Object>(tuples.size() * 2);
for(Tuple tuple: tuples) { for (Tuple tuple : tuples) {
tupleArgs.add(tuple.getScore()); tupleArgs.add(tuple.getScore());
tupleArgs.add(tuple.getValue()); tupleArgs.add(tuple.getValue());
} }

View File

@@ -7,23 +7,17 @@ import org.springframework.core.convert.converter.Converter;
/** /**
* Converts a List of values of one type to a List of values of another type * Converts a List of values of one type to a List of values of another type
* *
* @author Jennifer Hickey * @author Jennifer Hickey
* * @param <S> The type of elements in the List to convert
* @param <S> * @param <T> The type of elements in the converted List
* The type of elements in the List to convert
* @param <T>
* The type of elements in the converted List
*/ */
public class ListConverter<S, T> implements Converter<List<S>, List<T>> { public class ListConverter<S, T> implements Converter<List<S>, List<T>> {
private Converter<S, T> itemConverter; private Converter<S, T> itemConverter;
/** /**
* * @param itemConverter The {@link Converter} to use for converting individual List items
* @param itemConverter
* The {@link Converter} to use for converting individual List
* items
*/ */
public ListConverter(Converter<S, T> itemConverter) { public ListConverter(Converter<S, T> itemConverter) {
this.itemConverter = itemConverter; this.itemConverter = itemConverter;

View File

@@ -19,9 +19,8 @@ import org.springframework.core.convert.converter.Converter;
/** /**
* Converts Longs to Booleans * Converts Longs to Booleans
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
public class LongToBooleanConverter implements Converter<Long, Boolean> { public class LongToBooleanConverter implements Converter<Long, Boolean> {

View File

@@ -22,25 +22,18 @@ import java.util.Map;
import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.Converter;
/** /**
* Converts a Map of values of one key/value type to a Map of values of another * Converts a Map of values of one key/value type to a Map of values of another type
* type *
*
* @author Jennifer Hickey * @author Jennifer Hickey
* * @param <S> The type of keys and values in the Map to convert
* @param <S> * @param <T> The type of keys and values in the converted Map
* The type of keys and values in the Map to convert
* @param <T>
* The type of keys and values in the converted Map
*/ */
public class MapConverter<S, T> implements Converter<Map<S, S>, Map<T, T>> { public class MapConverter<S, T> implements Converter<Map<S, S>, Map<T, T>> {
private Converter<S, T> itemConverter; private Converter<S, T> itemConverter;
/** /**
* * @param itemConverter The {@link Converter} to use for converting individual Map keys and values
* @param itemConverter
* The {@link Converter} to use for converting individual Map
* keys and values
*/ */
public MapConverter(Converter<S, T> itemConverter) { public MapConverter(Converter<S, T> itemConverter) {
this.itemConverter = itemConverter; this.itemConverter = itemConverter;
@@ -57,8 +50,7 @@ public class MapConverter<S, T> implements Converter<Map<S, S>, Map<T, T>> {
results = new HashMap<T, T>(); results = new HashMap<T, T>();
} }
for (Map.Entry<S, S> result : source.entrySet()) { for (Map.Entry<S, S> result : source.entrySet()) {
results.put(itemConverter.convert(result.getKey()), results.put(itemConverter.convert(result.getKey()), itemConverter.convert(result.getValue()));
itemConverter.convert(result.getValue()));
} }
return results; return results;
} }

View File

@@ -23,23 +23,17 @@ import org.springframework.core.convert.converter.Converter;
/** /**
* Converts a Set of values of one type to a Set of values of another type * Converts a Set of values of one type to a Set of values of another type
* *
* @author Jennifer Hickey * @author Jennifer Hickey
* * @param <S> The type of elements in the Set to convert
* @param <S> * @param <T> The type of elements in the converted Set
* The type of elements in the Set to convert
* @param <T>
* The type of elements in the converted Set
*/ */
public class SetConverter<S, T> implements Converter<Set<S>, Set<T>> { public class SetConverter<S, T> implements Converter<Set<S>, Set<T>> {
private Converter<S, T> itemConverter; private Converter<S, T> itemConverter;
/** /**
* * @param itemConverter The {@link Converter} to use for converting individual Set items
* @param itemConverter
* The {@link Converter} to use for converting individual Set
* items
*/ */
public SetConverter(Converter<S, T> itemConverter) { public SetConverter(Converter<S, T> itemConverter) {
this.itemConverter = itemConverter; this.itemConverter = itemConverter;

View File

@@ -20,9 +20,8 @@ import org.springframework.data.redis.connection.DataType;
/** /**
* Converts Strings to {@link DataType}s * Converts Strings to {@link DataType}s
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
public class StringToDataTypeConverter implements Converter<String, DataType> { public class StringToDataTypeConverter implements Converter<String, DataType> {

View File

@@ -23,9 +23,8 @@ import org.springframework.data.redis.RedisSystemException;
/** /**
* Converts Strings to {@link Properties} * Converts Strings to {@link Properties}
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
public class StringToPropertiesConverter implements Converter<String, Properties> { public class StringToPropertiesConverter implements Converter<String, Properties> {

View File

@@ -25,14 +25,11 @@ import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.FutureResult; import org.springframework.data.redis.connection.FutureResult;
/** /**
* Converts the results of transaction exec using a supplied Queue of {@link FutureResult}s. * Converts the results of transaction exec using a supplied Queue of {@link FutureResult}s. Converts any Exception
* Converts any Exception objects returned in the list as well, using the supplied Exception * objects returned in the list as well, using the supplied Exception {@link Converter}
* {@link Converter} *
*
* @author Jennifer Hickey * @author Jennifer Hickey
* * @param <T> The type of {@link FutureResult} of the individual tx operations
* @param <T>
* The type of {@link FutureResult} of the individual tx operations
*/ */
public class TransactionResultConverter<T> implements Converter<List<Object>, List<Object>> { public class TransactionResultConverter<T> implements Converter<List<Object>, List<Object>> {
@@ -51,9 +48,8 @@ public class TransactionResultConverter<T> implements Converter<List<Object>, Li
return null; return null;
} }
if (execResults.size() != txResults.size()) { if (execResults.size() != txResults.size()) {
throw new IllegalArgumentException( throw new IllegalArgumentException("Incorrect number of transaction results. Expected: " + txResults.size()
"Incorrect number of transaction results. Expected: " + txResults.size() + " Actual: " + execResults.size());
+ " Actual: " + execResults.size());
} }
List<Object> convertedResults = new ArrayList<Object>(); List<Object> convertedResults = new ArrayList<Object>();
for (Object result : execResults) { for (Object result : execResults) {

View File

@@ -54,16 +54,15 @@ public class JedisConnectionFactory implements InitializingBean, DisposableBean,
private boolean convertPipelineAndTxResults = true; private boolean convertPipelineAndTxResults = true;
/** /**
* Constructs a new <code>JedisConnectionFactory</code> instance * Constructs a new <code>JedisConnectionFactory</code> instance with default settings (default connection pooling, no
* with default settings (default connection pooling, no shard information). * shard information).
*/ */
public JedisConnectionFactory() { public JedisConnectionFactory() {}
}
/** /**
* Constructs a new <code>JedisConnectionFactory</code> instance. * Constructs a new <code>JedisConnectionFactory</code> instance. Will override the other connection parameters passed
* Will override the other connection parameters passed to the factory. * to the factory.
* *
* @param shardInfo shard information * @param shardInfo shard information
*/ */
public JedisConnectionFactory(JedisShardInfo shardInfo) { public JedisConnectionFactory(JedisShardInfo shardInfo) {
@@ -71,19 +70,17 @@ public class JedisConnectionFactory implements InitializingBean, DisposableBean,
} }
/** /**
* Constructs a new <code>JedisConnectionFactory</code> instance using * Constructs a new <code>JedisConnectionFactory</code> instance using the given pool configuration.
* the given pool configuration. *
*
* @param poolConfig pool configuration * @param poolConfig pool configuration
*/ */
public JedisConnectionFactory(JedisPoolConfig poolConfig) { public JedisConnectionFactory(JedisPoolConfig poolConfig) {
this.poolConfig = poolConfig; this.poolConfig = poolConfig;
} }
/** /**
* Returns a Jedis instance to be used as a Redis connection. * Returns a Jedis instance to be used as a Redis connection. The instance can be newly created or retrieved from a
* The instance can be newly created or retrieved from a pool. * pool.
* *
* @return Jedis instance ready for wrapping into a {@link RedisConnection}. * @return Jedis instance ready for wrapping into a {@link RedisConnection}.
*/ */
@@ -102,9 +99,8 @@ public class JedisConnectionFactory implements InitializingBean, DisposableBean,
} }
/** /**
* Post process a newly retrieved connection. Useful for decorating or executing * Post process a newly retrieved connection. Useful for decorating or executing initialization commands on a new
* initialization commands on a new connection. * connection. This implementation simply returns the connection.
* This implementation simply returns the connection.
* *
* @param connection * @param connection
* @return processed connection * @return processed connection
@@ -145,20 +141,19 @@ public class JedisConnectionFactory implements InitializingBean, DisposableBean,
public JedisConnection getConnection() { public JedisConnection getConnection() {
Jedis jedis = fetchJedisConnector(); Jedis jedis = fetchJedisConnector();
JedisConnection connection = (usePool ? new JedisConnection(jedis, pool, dbIndex) : JedisConnection connection = (usePool ? new JedisConnection(jedis, pool, dbIndex) : new JedisConnection(jedis,
new JedisConnection(jedis, null, dbIndex)); null, dbIndex));
connection.setConvertPipelineAndTxResults(convertPipelineAndTxResults); connection.setConvertPipelineAndTxResults(convertPipelineAndTxResults);
return postProcessConnection(connection); return postProcessConnection(connection);
} }
public DataAccessException translateExceptionIfPossible(RuntimeException ex) { public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
return JedisConverters.toDataAccessException(ex); return JedisConverters.toDataAccessException(ex);
} }
/** /**
* Returns the Redis hostName. * Returns the Redis hostName.
* *
* @return Returns the hostName * @return Returns the hostName
*/ */
public String getHostName() { public String getHostName() {
@@ -213,7 +208,7 @@ public class JedisConnectionFactory implements InitializingBean, DisposableBean,
/** /**
* Returns the shardInfo. * Returns the shardInfo.
* *
* @return Returns the shardInfo * @return Returns the shardInfo
*/ */
public JedisShardInfo getShardInfo() { public JedisShardInfo getShardInfo() {
@@ -231,7 +226,7 @@ public class JedisConnectionFactory implements InitializingBean, DisposableBean,
/** /**
* Returns the timeout. * Returns the timeout.
* *
* @return Returns the timeout * @return Returns the timeout
*/ */
public int getTimeout() { public int getTimeout() {
@@ -247,7 +242,7 @@ public class JedisConnectionFactory implements InitializingBean, DisposableBean,
/** /**
* Indicates the use of a connection pool. * Indicates the use of a connection pool.
* *
* @return Returns the use of connection pooling. * @return Returns the use of connection pooling.
*/ */
public boolean getUsePool() { public boolean getUsePool() {
@@ -265,7 +260,7 @@ public class JedisConnectionFactory implements InitializingBean, DisposableBean,
/** /**
* Returns the poolConfig. * Returns the poolConfig.
* *
* @return Returns the poolConfig * @return Returns the poolConfig
*/ */
public JedisPoolConfig getPoolConfig() { public JedisPoolConfig getPoolConfig() {
@@ -281,10 +276,9 @@ public class JedisConnectionFactory implements InitializingBean, DisposableBean,
this.poolConfig = poolConfig; this.poolConfig = poolConfig;
} }
/** /**
* Returns the index of the database. * Returns the index of the database.
* *
* @return Returns the database index * @return Returns the database index
*/ */
public int getDatabase() { public int getDatabase() {
@@ -292,8 +286,7 @@ public class JedisConnectionFactory implements InitializingBean, DisposableBean,
} }
/** /**
* Sets the index of the database used by this connection factory. * Sets the index of the database used by this connection factory. Default is 0.
* Default is 0.
* *
* @param index database index * @param index database index
*/ */
@@ -303,10 +296,10 @@ public class JedisConnectionFactory implements InitializingBean, DisposableBean,
} }
/** /**
* Specifies if pipelined results should be converted to the expected data * Specifies if pipelined results should be converted to the expected data type. If false, results of
* type. If false, results of {@link JedisConnection#closePipeline()} and * {@link JedisConnection#closePipeline()} and {@link JedisConnection#exec()} will be of the type returned by the
* {@link JedisConnection#exec()} will be of the type returned by the Jedis driver * Jedis driver
* *
* @return Whether or not to convert pipeline and tx results * @return Whether or not to convert pipeline and tx results
*/ */
public boolean getConvertPipelineAndTxResults() { public boolean getConvertPipelineAndTxResults() {
@@ -314,13 +307,13 @@ public class JedisConnectionFactory implements InitializingBean, DisposableBean,
} }
/** /**
* Specifies if pipelined results should be converted to the expected data * Specifies if pipelined results should be converted to the expected data type. If false, results of
* type. If false, results of {@link JedisConnection#closePipeline()} and * {@link JedisConnection#closePipeline()} and {@link JedisConnection#exec()} will be of the type returned by the
* {@link JedisConnection#exec()} will be of the type returned by the Jedis driver * Jedis driver
* *
* @param convertPipelineAndTxResults Whether or not to convert pipeline and tx results * @param convertPipelineAndTxResults Whether or not to convert pipeline and tx results
*/ */
public void setConvertPipelineAndTxResults(boolean convertPipelineAndTxResults) { public void setConvertPipelineAndTxResults(boolean convertPipelineAndTxResults) {
this.convertPipelineAndTxResults = convertPipelineAndTxResults; this.convertPipelineAndTxResults = convertPipelineAndTxResults;
} }
} }

View File

@@ -38,9 +38,8 @@ import redis.clients.util.SafeEncoder;
/** /**
* Jedis type converters * Jedis type converters
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
abstract public class JedisConverters extends Converters { abstract public class JedisConverters extends Converters {
@@ -49,7 +48,7 @@ abstract public class JedisConverters extends Converters {
private static final SetConverter<String, byte[]> STRING_SET_TO_BYTE_SET; private static final SetConverter<String, byte[]> STRING_SET_TO_BYTE_SET;
private static final MapConverter<String, byte[]> STRING_MAP_TO_BYTE_MAP; private static final MapConverter<String, byte[]> STRING_MAP_TO_BYTE_MAP;
private static final SetConverter<redis.clients.jedis.Tuple, Tuple> TUPLE_SET_TO_TUPLE_SET; private static final SetConverter<redis.clients.jedis.Tuple, Tuple> TUPLE_SET_TO_TUPLE_SET;
private static final Converter<Exception,DataAccessException> EXCEPTION_CONVERTER = new JedisExceptionConverter(); private static final Converter<Exception, DataAccessException> EXCEPTION_CONVERTER = new JedisExceptionConverter();
static { static {
STRING_TO_BYTES = new Converter<String, byte[]>() { STRING_TO_BYTES = new Converter<String, byte[]>() {
@@ -89,7 +88,7 @@ abstract public class JedisConverters extends Converters {
return TUPLE_SET_TO_TUPLE_SET; return TUPLE_SET_TO_TUPLE_SET;
} }
public static Converter<Exception,DataAccessException> exceptionConverter() { public static Converter<Exception, DataAccessException> exceptionConverter() {
return EXCEPTION_CONVERTER; return EXCEPTION_CONVERTER;
} }

View File

@@ -30,9 +30,8 @@ import redis.clients.jedis.exceptions.JedisException;
/** /**
* Converts Exceptions thrown from Jedis to {@link DataAccessException}s * Converts Exceptions thrown from Jedis to {@link DataAccessException}s
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
public class JedisExceptionConverter implements Converter<Exception, DataAccessException> { public class JedisExceptionConverter implements Converter<Exception, DataAccessException> {

View File

@@ -35,33 +35,27 @@ class JedisMessageListener extends BinaryJedisPubSub {
this.listener = listener; this.listener = listener;
} }
public void onMessage(byte[] channel, byte[] message) { public void onMessage(byte[] channel, byte[] message) {
listener.onMessage(new DefaultMessage(channel, message), null); listener.onMessage(new DefaultMessage(channel, message), null);
} }
public void onPMessage(byte[] pattern, byte[] channel, byte[] message) { public void onPMessage(byte[] pattern, byte[] channel, byte[] message) {
listener.onMessage(new DefaultMessage(channel, message), pattern); listener.onMessage(new DefaultMessage(channel, message), pattern);
} }
public void onPSubscribe(byte[] pattern, int subscribedChannels) { public void onPSubscribe(byte[] pattern, int subscribedChannels) {
// no-op // no-op
} }
public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { public void onPUnsubscribe(byte[] pattern, int subscribedChannels) {
// no-op // no-op
} }
public void onSubscribe(byte[] channel, int subscribedChannels) { public void onSubscribe(byte[] channel, int subscribedChannels) {
// no-op // no-op
} }
public void onUnsubscribe(byte[] channel, int subscribedChannels) { public void onUnsubscribe(byte[] channel, int subscribedChannels) {
// no-op // no-op
} }
} }

View File

@@ -24,11 +24,9 @@ import org.springframework.data.redis.connection.ReturnType;
import redis.clients.util.SafeEncoder; import redis.clients.util.SafeEncoder;
/** /**
* Converts the value returned by Jedis script eval to the expected * Converts the value returned by Jedis script eval to the expected {@link ReturnType}
* {@link ReturnType} *
*
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
public class JedisScriptReturnConverter implements Converter<Object, Object> { public class JedisScriptReturnConverter implements Converter<Object, Object> {

View File

@@ -34,43 +34,36 @@ class JedisSubscription extends AbstractSubscription {
this.jedisPubSub = jedisPubSub; this.jedisPubSub = jedisPubSub;
} }
protected void doClose() { protected void doClose() {
if(!getChannels().isEmpty()) { if (!getChannels().isEmpty()) {
jedisPubSub.unsubscribe(); jedisPubSub.unsubscribe();
} }
if(!getPatterns().isEmpty()) { if (!getPatterns().isEmpty()) {
jedisPubSub.punsubscribe(); jedisPubSub.punsubscribe();
} }
} }
protected void doPsubscribe(byte[]... patterns) { protected void doPsubscribe(byte[]... patterns) {
jedisPubSub.psubscribe(patterns); jedisPubSub.psubscribe(patterns);
} }
protected void doPUnsubscribe(boolean all, byte[]... patterns) { protected void doPUnsubscribe(boolean all, byte[]... patterns) {
if (all) { if (all) {
jedisPubSub.punsubscribe(); jedisPubSub.punsubscribe();
} } else {
else {
jedisPubSub.punsubscribe(patterns); jedisPubSub.punsubscribe(patterns);
} }
} }
protected void doSubscribe(byte[]... channels) { protected void doSubscribe(byte[]... channels) {
jedisPubSub.subscribe(channels); jedisPubSub.subscribe(channels);
} }
protected void doUnsubscribe(boolean all, byte[]... channels) { protected void doUnsubscribe(boolean all, byte[]... channels) {
if (all) { if (all) {
jedisPubSub.unsubscribe(); jedisPubSub.unsubscribe();
} } else {
else {
jedisPubSub.unsubscribe(channels); jedisPubSub.unsubscribe(channels);
} }
} }
} }

View File

@@ -52,9 +52,8 @@ import redis.clients.jedis.exceptions.JedisException;
import redis.clients.util.SafeEncoder; import redis.clients.util.SafeEncoder;
/** /**
* Helper class featuring methods for Jedis connection handling, providing support for exception translation. * Helper class featuring methods for Jedis connection handling, providing support for exception translation. Deprecated
* * in favor of {@link JedisConverters}
* Deprecated in favor of {@link JedisConverters}
* *
* @author Costin Leau * @author Costin Leau
* @author Jennifer Hickey * @author Jennifer Hickey
@@ -283,28 +282,28 @@ public abstract class JedisUtils {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
static Object convertScriptReturn(ReturnType returnType, Object result) { static Object convertScriptReturn(ReturnType returnType, Object result) {
if(result instanceof String) { if (result instanceof String) {
//evalsha converts byte[] to String. Convert back for consistency // evalsha converts byte[] to String. Convert back for consistency
return SafeEncoder.encode((String)result); return SafeEncoder.encode((String) result);
} }
if(returnType == ReturnType.STATUS) { if (returnType == ReturnType.STATUS) {
return JedisUtils.asString((byte[])result); return JedisUtils.asString((byte[]) result);
} }
if(returnType == ReturnType.BOOLEAN) { if (returnType == ReturnType.BOOLEAN) {
// Lua false comes back as a null bulk reply // Lua false comes back as a null bulk reply
if(result == null) { if (result == null) {
return Boolean.FALSE; return Boolean.FALSE;
} }
return ((Long)result == 1); return ((Long) result == 1);
} }
if(returnType == ReturnType.MULTI) { if (returnType == ReturnType.MULTI) {
List<Object> resultList = (List<Object>) result; List<Object> resultList = (List<Object>) result;
List<Object> convertedResults = new ArrayList<Object>(); List<Object> convertedResults = new ArrayList<Object>();
for(Object res: resultList) { for (Object res : resultList) {
if(res instanceof String) { if (res instanceof String) {
//evalsha converts byte[] to String. Convert back for consistency // evalsha converts byte[] to String. Convert back for consistency
convertedResults.add(SafeEncoder.encode((String)res)); convertedResults.add(SafeEncoder.encode((String) res));
}else { } else {
convertedResults.add(res); convertedResults.add(res);
} }
} }
@@ -313,4 +312,4 @@ public abstract class JedisUtils {
return result; return result;
} }
} }

View File

@@ -64,14 +64,13 @@ public class JredisConnection implements RedisConnection {
private boolean broken = false; private boolean broken = false;
static { static {
SERVICE_REQUEST = ReflectionUtils.findMethod(JRedisSupport.class, "serviceRequest", Command.class, SERVICE_REQUEST = ReflectionUtils.findMethod(JRedisSupport.class, "serviceRequest", Command.class, byte[][].class);
byte[][].class);
ReflectionUtils.makeAccessible(SERVICE_REQUEST); ReflectionUtils.makeAccessible(SERVICE_REQUEST);
} }
/** /**
* Constructs a new <code>JredisConnection</code> instance. * Constructs a new <code>JredisConnection</code> instance.
* *
* @param jredis JRedis connection * @param jredis JRedis connection
*/ */
public JredisConnection(JRedis jredis) { public JredisConnection(JRedis jredis) {
@@ -90,7 +89,7 @@ public class JredisConnection implements RedisConnection {
} }
if (ex instanceof ClientRuntimeException) { if (ex instanceof ClientRuntimeException) {
if(ex instanceof NotConnectedException || ex instanceof ConnectionException) { if (ex instanceof NotConnectedException || ex instanceof ConnectionException) {
broken = true; broken = true;
} }
return JredisUtils.convertJredisAccessException((ClientRuntimeException) ex); return JredisUtils.convertJredisAccessException((ClientRuntimeException) ex);
@@ -115,7 +114,7 @@ public class JredisConnection implements RedisConnection {
} }
public void close() throws RedisSystemException { public void close() throws RedisSystemException {
if(isClosed()) { if (isClosed()) {
return; return;
} }
isClosed = true; isClosed = true;
@@ -123,7 +122,7 @@ public class JredisConnection implements RedisConnection {
if (pool != null) { if (pool != null) {
if (!broken) { if (!broken) {
pool.returnResource(jredis); pool.returnResource(jredis);
}else { } else {
pool.returnBrokenResource(jredis); pool.returnBrokenResource(jredis);
} }
return; return;
@@ -141,32 +140,26 @@ public class JredisConnection implements RedisConnection {
return jredis; return jredis;
} }
public boolean isClosed() { public boolean isClosed() {
return isClosed; return isClosed;
} }
public boolean isQueueing() { public boolean isQueueing() {
return false; return false;
} }
public boolean isPipelined() { public boolean isPipelined() {
return false; return false;
} }
public void openPipeline() { public void openPipeline() {
throw new UnsupportedOperationException("Pipelining not supported by JRedis"); throw new UnsupportedOperationException("Pipelining not supported by JRedis");
} }
public List<Object> closePipeline() { public List<Object> closePipeline() {
return Collections.emptyList(); return Collections.emptyList();
} }
public List<byte[]> sort(byte[] key, SortParameters params) { public List<byte[]> sort(byte[] key, SortParameters params) {
Sort sort = jredis.sort(key); Sort sort = jredis.sort(key);
JredisUtils.applySortingParams(sort, params, null); JredisUtils.applySortingParams(sort, params, null);
@@ -177,7 +170,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long sort(byte[] key, SortParameters params, byte[] storeKey) { public Long sort(byte[] key, SortParameters params, byte[] storeKey) {
Sort sort = jredis.sort(key); Sort sort = jredis.sort(key);
JredisUtils.applySortingParams(sort, params, storeKey); JredisUtils.applySortingParams(sort, params, storeKey);
@@ -188,16 +180,14 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long dbSize() { public Long dbSize() {
try { try {
return (Long)jredis.dbsize(); return (Long) jredis.dbsize();
} catch (Exception ex) { } catch (Exception ex) {
throw convertJredisAccessException(ex); throw convertJredisAccessException(ex);
} }
} }
public void flushDb() { public void flushDb() {
try { try {
jredis.flushdb(); jredis.flushdb();
@@ -206,7 +196,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public void flushAll() { public void flushAll() {
try { try {
jredis.flushall(); jredis.flushall();
@@ -215,7 +204,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public byte[] echo(byte[] message) { public byte[] echo(byte[] message) {
try { try {
return jredis.echo(message); return jredis.echo(message);
@@ -224,7 +212,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public String ping() { public String ping() {
try { try {
jredis.ping(); jredis.ping();
@@ -234,7 +221,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public void bgSave() { public void bgSave() {
try { try {
jredis.bgsave(); jredis.bgsave();
@@ -243,7 +229,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public void bgWriteAof() { public void bgWriteAof() {
try { try {
jredis.bgrewriteaof(); jredis.bgrewriteaof();
@@ -252,7 +237,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public void save() { public void save() {
try { try {
jredis.save(); jredis.save();
@@ -261,12 +245,10 @@ public class JredisConnection implements RedisConnection {
} }
} }
public List<String> getConfig(String pattern) { public List<String> getConfig(String pattern) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Properties info() { public Properties info() {
try { try {
return JredisUtils.info(jredis.info()); return JredisUtils.info(jredis.info());
@@ -275,36 +257,30 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Properties info(String section) { public Properties info(String section) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long lastSave() { public Long lastSave() {
try { try {
return (Long)jredis.lastsave(); return (Long) jredis.lastsave();
} catch (Exception ex) { } catch (Exception ex) {
throw convertJredisAccessException(ex); throw convertJredisAccessException(ex);
} }
} }
public void setConfig(String param, String value) { public void setConfig(String param, String value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public void resetConfigStats() { public void resetConfigStats() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public void shutdown() { public void shutdown() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long del(byte[]... keys) { public Long del(byte[]... keys) {
try { try {
return jredis.del(keys); return jredis.del(keys);
@@ -313,7 +289,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public void discard() { public void discard() {
try { try {
jredis.discard(); jredis.discard();
@@ -322,12 +297,10 @@ public class JredisConnection implements RedisConnection {
} }
} }
public List<Object> exec() { public List<Object> exec() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Boolean exists(byte[] key) { public Boolean exists(byte[] key) {
try { try {
return jredis.exists(key); return jredis.exists(key);
@@ -336,7 +309,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Boolean expire(byte[] key, long seconds) { public Boolean expire(byte[] key, long seconds) {
try { try {
return jredis.expire(key, (int) seconds); return jredis.expire(key, (int) seconds);
@@ -345,7 +317,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Boolean expireAt(byte[] key, long unixTime) { public Boolean expireAt(byte[] key, long unixTime) {
try { try {
return jredis.expireat(key, unixTime); return jredis.expireat(key, unixTime);
@@ -382,18 +353,14 @@ public class JredisConnection implements RedisConnection {
} }
} }
public void multi() { public void multi() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Boolean persist(byte[] key) { public Boolean persist(byte[] key) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Boolean move(byte[] key, int dbIndex) { public Boolean move(byte[] key, int dbIndex) {
try { try {
return jredis.move(key, dbIndex); return jredis.move(key, dbIndex);
@@ -402,7 +369,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public byte[] randomKey() { public byte[] randomKey() {
try { try {
return jredis.randomkey(); return jredis.randomkey();
@@ -411,7 +377,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public void rename(byte[] oldName, byte[] newName) { public void rename(byte[] oldName, byte[] newName) {
try { try {
jredis.rename(oldName, newName); jredis.rename(oldName, newName);
@@ -420,7 +385,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Boolean renameNX(byte[] oldName, byte[] newName) { public Boolean renameNX(byte[] oldName, byte[] newName) {
try { try {
return jredis.renamenx(oldName, newName); return jredis.renamenx(oldName, newName);
@@ -429,12 +393,10 @@ public class JredisConnection implements RedisConnection {
} }
} }
public void select(int dbIndex) { public void select(int dbIndex) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long ttl(byte[] key) { public Long ttl(byte[] key) {
try { try {
return jredis.ttl(key); return jredis.ttl(key);
@@ -443,7 +405,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public DataType type(byte[] key) { public DataType type(byte[] key) {
try { try {
return JredisUtils.convertDataType(jredis.type(key)); return JredisUtils.convertDataType(jredis.type(key));
@@ -452,12 +413,10 @@ public class JredisConnection implements RedisConnection {
} }
} }
public void unwatch() { public void unwatch() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public void watch(byte[]... keys) { public void watch(byte[]... keys) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@@ -466,7 +425,6 @@ public class JredisConnection implements RedisConnection {
// String operations // String operations
// //
public byte[] get(byte[] key) { public byte[] get(byte[] key) {
try { try {
return jredis.get(key); return jredis.get(key);
@@ -475,7 +433,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public void set(byte[] key, byte[] value) { public void set(byte[] key, byte[] value) {
try { try {
jredis.set(key, value); jredis.set(key, value);
@@ -484,7 +441,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public byte[] getSet(byte[] key, byte[] value) { public byte[] getSet(byte[] key, byte[] value) {
try { try {
return jredis.getset(key, value); return jredis.getset(key, value);
@@ -493,7 +449,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long append(byte[] key, byte[] value) { public Long append(byte[] key, byte[] value) {
try { try {
return jredis.append(key, value); return jredis.append(key, value);
@@ -502,7 +457,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public List<byte[]> mGet(byte[]... keys) { public List<byte[]> mGet(byte[]... keys) {
try { try {
return jredis.mget(keys); return jredis.mget(keys);
@@ -511,7 +465,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public void mSet(Map<byte[], byte[]> tuple) { public void mSet(Map<byte[], byte[]> tuple) {
try { try {
jredis.mset(tuple); jredis.mset(tuple);
@@ -520,7 +473,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Boolean mSetNX(Map<byte[], byte[]> tuple) { public Boolean mSetNX(Map<byte[], byte[]> tuple) {
try { try {
return jredis.msetnx(tuple); return jredis.msetnx(tuple);
@@ -529,12 +481,10 @@ public class JredisConnection implements RedisConnection {
} }
} }
public void setEx(byte[] key, long seconds, byte[] value) { public void setEx(byte[] key, long seconds, byte[] value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Boolean setNX(byte[] key, byte[] value) { public Boolean setNX(byte[] key, byte[] value) {
try { try {
return jredis.setnx(key, value); return jredis.setnx(key, value);
@@ -543,7 +493,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public byte[] getRange(byte[] key, long start, long end) { public byte[] getRange(byte[] key, long start, long end) {
try { try {
return jredis.substr(key, start, end); return jredis.substr(key, start, end);
@@ -552,7 +501,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long decr(byte[] key) { public Long decr(byte[] key) {
try { try {
return jredis.decr(key); return jredis.decr(key);
@@ -561,7 +509,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long decrBy(byte[] key, long value) { public Long decrBy(byte[] key, long value) {
try { try {
return jredis.decrby(key, (int) value); return jredis.decrby(key, (int) value);
@@ -570,7 +517,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long incr(byte[] key) { public Long incr(byte[] key) {
try { try {
return jredis.incr(key); return jredis.incr(key);
@@ -579,7 +525,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long incrBy(byte[] key, long value) { public Long incrBy(byte[] key, long value) {
try { try {
return jredis.incrby(key, (int) value); return jredis.incrby(key, (int) value);
@@ -588,21 +533,18 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Double incrBy(byte[] key, double value) { public Double incrBy(byte[] key, double value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Boolean getBit(byte[] key, long offset) { public Boolean getBit(byte[] key, long offset) {
try { try {
return jredis.getbit(key, (int)offset); return jredis.getbit(key, (int) offset);
} catch(Exception ex) { } catch (Exception ex) {
throw convertJredisAccessException(ex); throw convertJredisAccessException(ex);
} }
} }
public void setBit(byte[] key, long offset, boolean value) { public void setBit(byte[] key, long offset, boolean value) {
try { try {
jredis.setbit(key, (int) offset, value); jredis.setbit(key, (int) offset, value);
@@ -611,27 +553,22 @@ public class JredisConnection implements RedisConnection {
} }
} }
public void setRange(byte[] key, byte[] value, long start) { public void setRange(byte[] key, byte[] value, long start) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long strLen(byte[] key) { public Long strLen(byte[] key) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long bitCount(byte[] key) { public Long bitCount(byte[] key) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long bitCount(byte[] key, long begin, long end) { public Long bitCount(byte[] key, long begin, long end) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long bitOp(BitOperation op, byte[] destination, byte[]... keys) { public Long bitOp(BitOperation op, byte[] destination, byte[]... keys) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@@ -640,17 +577,14 @@ public class JredisConnection implements RedisConnection {
// List commands // List commands
// //
public List<byte[]> bLPop(int timeout, byte[]... keys) { public List<byte[]> bLPop(int timeout, byte[]... keys) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public List<byte[]> bRPop(int timeout, byte[]... keys) { public List<byte[]> bRPop(int timeout, byte[]... keys) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public byte[] lIndex(byte[] key, long index) { public byte[] lIndex(byte[] key, long index) {
try { try {
return jredis.lindex(key, index); return jredis.lindex(key, index);
@@ -659,7 +593,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long lLen(byte[] key) { public Long lLen(byte[] key) {
try { try {
return jredis.llen(key); return jredis.llen(key);
@@ -668,7 +601,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public byte[] lPop(byte[] key) { public byte[] lPop(byte[] key) {
try { try {
return jredis.lpop(key); return jredis.lpop(key);
@@ -677,9 +609,8 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long lPush(byte[] key, byte[]... values) { public Long lPush(byte[] key, byte[]... values) {
if(values.length > 1) { if (values.length > 1) {
throw new UnsupportedOperationException("lPush of multiple fields not supported"); throw new UnsupportedOperationException("lPush of multiple fields not supported");
} }
try { try {
@@ -690,7 +621,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public List<byte[]> lRange(byte[] key, long start, long end) { public List<byte[]> lRange(byte[] key, long start, long end) {
try { try {
List<byte[]> lrange = jredis.lrange(key, start, end); List<byte[]> lrange = jredis.lrange(key, start, end);
@@ -701,7 +631,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long lRem(byte[] key, long count, byte[] value) { public Long lRem(byte[] key, long count, byte[] value) {
try { try {
return jredis.lrem(key, value, (int) count); return jredis.lrem(key, value, (int) count);
@@ -710,7 +639,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public void lSet(byte[] key, long index, byte[] value) { public void lSet(byte[] key, long index, byte[] value) {
try { try {
jredis.lset(key, index, value); jredis.lset(key, index, value);
@@ -719,7 +647,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public void lTrim(byte[] key, long start, long end) { public void lTrim(byte[] key, long start, long end) {
try { try {
jredis.ltrim(key, start, end); jredis.ltrim(key, start, end);
@@ -728,7 +655,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public byte[] rPop(byte[] key) { public byte[] rPop(byte[] key) {
try { try {
return jredis.rpop(key); return jredis.rpop(key);
@@ -737,7 +663,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public byte[] rPopLPush(byte[] srcKey, byte[] dstKey) { public byte[] rPopLPush(byte[] srcKey, byte[] dstKey) {
try { try {
return jredis.rpoplpush(srcKey, dstKey); return jredis.rpoplpush(srcKey, dstKey);
@@ -746,9 +671,8 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long rPush(byte[] key, byte[]... values) { public Long rPush(byte[] key, byte[]... values) {
if(values.length > 1) { if (values.length > 1) {
throw new UnsupportedOperationException("rPush of multiple fields not supported"); throw new UnsupportedOperationException("rPush of multiple fields not supported");
} }
try { try {
@@ -759,34 +683,28 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long lInsert(byte[] key, Position where, byte[] pivot, byte[] value) { public Long lInsert(byte[] key, Position where, byte[] pivot, byte[] value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public byte[] bRPopLPush(int timeout, byte[] srcKey, byte[] dstKey) { public byte[] bRPopLPush(int timeout, byte[] srcKey, byte[] dstKey) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long lPushX(byte[] key, byte[] value) { public Long lPushX(byte[] key, byte[] value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long rPushX(byte[] key, byte[] value) { public Long rPushX(byte[] key, byte[] value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
// //
// Set commands // Set commands
// //
public Long sAdd(byte[] key, byte[]... values) { public Long sAdd(byte[] key, byte[]... values) {
if(values.length > 1) { if (values.length > 1) {
throw new UnsupportedOperationException("sAdd of multiple fields not supported"); throw new UnsupportedOperationException("sAdd of multiple fields not supported");
} }
try { try {
@@ -796,7 +714,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long sCard(byte[] key) { public Long sCard(byte[] key) {
try { try {
return jredis.scard(key); return jredis.scard(key);
@@ -805,7 +722,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Set<byte[]> sDiff(byte[]... keys) { public Set<byte[]> sDiff(byte[]... keys) {
byte[] destKey = keys[0]; byte[] destKey = keys[0];
byte[][] sets = Arrays.copyOfRange(keys, 1, keys.length); byte[][] sets = Arrays.copyOfRange(keys, 1, keys.length);
@@ -818,7 +734,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long sDiffStore(byte[] destKey, byte[]... keys) { public Long sDiffStore(byte[] destKey, byte[]... keys) {
try { try {
jredis.sdiffstore(destKey, keys); jredis.sdiffstore(destKey, keys);
@@ -828,7 +743,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Set<byte[]> sInter(byte[]... keys) { public Set<byte[]> sInter(byte[]... keys) {
byte[] set1 = keys[0]; byte[] set1 = keys[0];
byte[][] sets = Arrays.copyOfRange(keys, 1, keys.length); byte[][] sets = Arrays.copyOfRange(keys, 1, keys.length);
@@ -841,7 +755,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long sInterStore(byte[] destKey, byte[]... keys) { public Long sInterStore(byte[] destKey, byte[]... keys) {
try { try {
jredis.sinterstore(destKey, keys); jredis.sinterstore(destKey, keys);
@@ -851,7 +764,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Boolean sIsMember(byte[] key, byte[] value) { public Boolean sIsMember(byte[] key, byte[] value) {
try { try {
return jredis.sismember(key, value); return jredis.sismember(key, value);
@@ -860,7 +772,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Set<byte[]> sMembers(byte[] key) { public Set<byte[]> sMembers(byte[] key) {
try { try {
return new LinkedHashSet<byte[]>(jredis.smembers(key)); return new LinkedHashSet<byte[]>(jredis.smembers(key));
@@ -869,7 +780,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Boolean sMove(byte[] srcKey, byte[] destKey, byte[] value) { public Boolean sMove(byte[] srcKey, byte[] destKey, byte[] value) {
try { try {
return jredis.smove(srcKey, destKey, value); return jredis.smove(srcKey, destKey, value);
@@ -878,7 +788,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public byte[] sPop(byte[] key) { public byte[] sPop(byte[] key) {
try { try {
return jredis.spop(key); return jredis.spop(key);
@@ -887,7 +796,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public byte[] sRandMember(byte[] key) { public byte[] sRandMember(byte[] key) {
try { try {
return jredis.srandmember(key); return jredis.srandmember(key);
@@ -896,14 +804,12 @@ public class JredisConnection implements RedisConnection {
} }
} }
public List<byte[]> sRandMember(byte[] key, long count) { public List<byte[]> sRandMember(byte[] key, long count) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long sRem(byte[] key, byte[]... values) { public Long sRem(byte[] key, byte[]... values) {
if(values.length > 1) { if (values.length > 1) {
throw new UnsupportedOperationException("sRem of multiple fields not supported"); throw new UnsupportedOperationException("sRem of multiple fields not supported");
} }
try { try {
@@ -913,7 +819,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Set<byte[]> sUnion(byte[]... keys) { public Set<byte[]> sUnion(byte[]... keys) {
byte[] set1 = keys[0]; byte[] set1 = keys[0];
byte[][] sets = Arrays.copyOfRange(keys, 1, keys.length); byte[][] sets = Arrays.copyOfRange(keys, 1, keys.length);
@@ -925,7 +830,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long sUnionStore(byte[] destKey, byte[]... keys) { public Long sUnionStore(byte[] destKey, byte[]... keys) {
try { try {
jredis.sunionstore(destKey, keys); jredis.sunionstore(destKey, keys);
@@ -935,12 +839,10 @@ public class JredisConnection implements RedisConnection {
} }
} }
// //
// ZSet commands // ZSet commands
// //
public Boolean zAdd(byte[] key, double score, byte[] value) { public Boolean zAdd(byte[] key, double score, byte[] value) {
try { try {
return jredis.zadd(key, score, value); return jredis.zadd(key, score, value);
@@ -961,7 +863,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long zCount(byte[] key, double min, double max) { public Long zCount(byte[] key, double min, double max) {
try { try {
return jredis.zcount(key, min, max); return jredis.zcount(key, min, max);
@@ -970,7 +871,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Double zIncrBy(byte[] key, double increment, byte[] value) { public Double zIncrBy(byte[] key, double increment, byte[] value) {
try { try {
return jredis.zincrby(key, increment, value); return jredis.zincrby(key, increment, value);
@@ -979,17 +879,14 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long zInterStore(byte[] destKey, Aggregate aggregate, int[] weights, byte[]... sets) { public Long zInterStore(byte[] destKey, Aggregate aggregate, int[] weights, byte[]... sets) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long zInterStore(byte[] destKey, byte[]... sets) { public Long zInterStore(byte[] destKey, byte[]... sets) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Set<byte[]> zRange(byte[] key, long start, long end) { public Set<byte[]> zRange(byte[] key, long start, long end) {
try { try {
return new LinkedHashSet<byte[]>(jredis.zrange(key, start, end)); return new LinkedHashSet<byte[]>(jredis.zrange(key, start, end));
@@ -998,12 +895,10 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Set<Tuple> zRangeWithScores(byte[] key, long start, long end) { public Set<Tuple> zRangeWithScores(byte[] key, long start, long end) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Set<byte[]> zRangeByScore(byte[] key, double min, double max) { public Set<byte[]> zRangeByScore(byte[] key, double min, double max) {
try { try {
return new LinkedHashSet<byte[]>(jredis.zrangebyscore(key, min, max)); return new LinkedHashSet<byte[]>(jredis.zrangebyscore(key, min, max));
@@ -1012,42 +907,34 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Set<Tuple> zRangeByScoreWithScores(byte[] key, double min, double max) { public Set<Tuple> zRangeByScoreWithScores(byte[] key, double min, double max) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Set<byte[]> zRangeByScore(byte[] key, double min, double max, long offset, long count) { public Set<byte[]> zRangeByScore(byte[] key, double min, double max, long offset, long count) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Set<Tuple> zRangeByScoreWithScores(byte[] key, double min, double max, long offset, long count) { public Set<Tuple> zRangeByScoreWithScores(byte[] key, double min, double max, long offset, long count) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Set<byte[]> zRevRangeByScore(byte[] key, double min, double max, long offset, long count) { public Set<byte[]> zRevRangeByScore(byte[] key, double min, double max, long offset, long count) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Set<byte[]> zRevRangeByScore(byte[] key, double min, double max) { public Set<byte[]> zRevRangeByScore(byte[] key, double min, double max) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Set<Tuple> zRevRangeByScoreWithScores(byte[] key, double min, double max, long offset, long count) { public Set<Tuple> zRevRangeByScoreWithScores(byte[] key, double min, double max, long offset, long count) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Set<Tuple> zRevRangeByScoreWithScores(byte[] key, double min, double max) { public Set<Tuple> zRevRangeByScoreWithScores(byte[] key, double min, double max) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long zRank(byte[] key, byte[] value) { public Long zRank(byte[] key, byte[] value) {
try { try {
return jredis.zrank(key, value); return jredis.zrank(key, value);
@@ -1056,9 +943,8 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long zRem(byte[] key, byte[]... values) { public Long zRem(byte[] key, byte[]... values) {
if(values.length > 1) { if (values.length > 1) {
throw new UnsupportedOperationException("zRem of multiple fields not supported"); throw new UnsupportedOperationException("zRem of multiple fields not supported");
} }
try { try {
@@ -1068,7 +954,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long zRemRange(byte[] key, long start, long end) { public Long zRemRange(byte[] key, long start, long end) {
try { try {
return jredis.zremrangebyrank(key, start, end); return jredis.zremrangebyrank(key, start, end);
@@ -1077,7 +962,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long zRemRangeByScore(byte[] key, double min, double max) { public Long zRemRangeByScore(byte[] key, double min, double max) {
try { try {
return jredis.zremrangebyscore(key, min, max); return jredis.zremrangebyscore(key, min, max);
@@ -1086,7 +970,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Set<byte[]> zRevRange(byte[] key, long start, long end) { public Set<byte[]> zRevRange(byte[] key, long start, long end) {
try { try {
return new LinkedHashSet<byte[]>(jredis.zrevrange(key, start, end)); return new LinkedHashSet<byte[]>(jredis.zrevrange(key, start, end));
@@ -1095,12 +978,10 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Set<Tuple> zRevRangeWithScores(byte[] key, long start, long end) { public Set<Tuple> zRevRangeWithScores(byte[] key, long start, long end) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long zRevRank(byte[] key, byte[] value) { public Long zRevRank(byte[] key, byte[] value) {
try { try {
return jredis.zrevrank(key, value); return jredis.zrevrank(key, value);
@@ -1109,7 +990,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Double zScore(byte[] key, byte[] value) { public Double zScore(byte[] key, byte[] value) {
try { try {
return jredis.zscore(key, value); return jredis.zscore(key, value);
@@ -1118,24 +998,20 @@ public class JredisConnection implements RedisConnection {
} }
} }
// //
// Hash commands // Hash commands
// //
public Long zUnionStore(byte[] destKey, Aggregate aggregate, int[] weights, byte[]... sets) { public Long zUnionStore(byte[] destKey, Aggregate aggregate, int[] weights, byte[]... sets) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long zUnionStore(byte[] destKey, byte[]... sets) { public Long zUnionStore(byte[] destKey, byte[]... sets) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long hDel(byte[] key, byte[]... fields) { public Long hDel(byte[] key, byte[]... fields) {
if(fields.length > 1) { if (fields.length > 1) {
throw new UnsupportedOperationException("hDel of multiple fields not supported"); throw new UnsupportedOperationException("hDel of multiple fields not supported");
} }
try { try {
@@ -1145,7 +1021,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Boolean hExists(byte[] key, byte[] field) { public Boolean hExists(byte[] key, byte[] field) {
try { try {
return jredis.hexists(key, field); return jredis.hexists(key, field);
@@ -1154,7 +1029,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public byte[] hGet(byte[] key, byte[] field) { public byte[] hGet(byte[] key, byte[] field) {
try { try {
return jredis.hget(key, field); return jredis.hget(key, field);
@@ -1163,7 +1037,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Map<byte[], byte[]> hGetAll(byte[] key) { public Map<byte[], byte[]> hGetAll(byte[] key) {
try { try {
return jredis.hgetall(key); return jredis.hgetall(key);
@@ -1172,7 +1045,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long hIncrBy(byte[] key, byte[] field, long delta) { public Long hIncrBy(byte[] key, byte[] field, long delta) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@@ -1189,7 +1061,6 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Long hLen(byte[] key) { public Long hLen(byte[] key) {
try { try {
return jredis.hlen(key); return jredis.hlen(key);
@@ -1198,17 +1069,14 @@ public class JredisConnection implements RedisConnection {
} }
} }
public List<byte[]> hMGet(byte[] key, byte[]... fields) { public List<byte[]> hMGet(byte[] key, byte[]... fields) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public void hMSet(byte[] key, Map<byte[], byte[]> values) { public void hMSet(byte[] key, Map<byte[], byte[]> values) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Boolean hSet(byte[] key, byte[] field, byte[] value) { public Boolean hSet(byte[] key, byte[] field, byte[] value) {
try { try {
return jredis.hset(key, field, value); return jredis.hset(key, field, value);
@@ -1217,12 +1085,10 @@ public class JredisConnection implements RedisConnection {
} }
} }
public Boolean hSetNX(byte[] key, byte[] field, byte[] value) { public Boolean hSetNX(byte[] key, byte[] field, byte[] value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public List<byte[]> hVals(byte[] key) { public List<byte[]> hVals(byte[] key) {
try { try {
return jredis.hvals(key); return jredis.hvals(key);
@@ -1235,31 +1101,25 @@ public class JredisConnection implements RedisConnection {
// PubSub commands // PubSub commands
// //
public Subscription getSubscription() { public Subscription getSubscription() {
return null; return null;
} }
public boolean isSubscribed() { public boolean isSubscribed() {
return false; return false;
} }
public void pSubscribe(MessageListener listener, byte[]... patterns) { public void pSubscribe(MessageListener listener, byte[]... patterns) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
public Long publish(byte[] channel, byte[] message) { public Long publish(byte[] channel, byte[] message) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
//
// // Scripting commands
// Scripting commands //
//
public void subscribe(MessageListener listener, byte[]... channels) { public void subscribe(MessageListener listener, byte[]... channels) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
@@ -1288,4 +1148,4 @@ public class JredisConnection implements RedisConnection {
public <T> T evalSha(String scriptSha1, ReturnType returnType, int numKeys, byte[]... keysAndArgs) { public <T> T evalSha(String scriptSha1, ReturnType returnType, int numKeys, byte[]... keysAndArgs) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
} }

View File

@@ -32,7 +32,7 @@ import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
* Connection factory using creating <a href="http://github.com/alphazero/jredis">JRedis</a> based connections. * Connection factory using creating <a href="http://github.com/alphazero/jredis">JRedis</a> based connections.
* *
* @author Costin Leau * @author Costin Leau
* @author Jennifer Hickey * @author Jennifer Hickey
@@ -52,23 +52,21 @@ public class JredisConnectionFactory implements InitializingBean, DisposableBean
private static final int DEFAULT_REDIS_DB = 0; private static final int DEFAULT_REDIS_DB = 0;
private static final byte[] DEFAULT_REDIS_PASSWORD = null; private static final byte[] DEFAULT_REDIS_PASSWORD = null;
/** /**
* Constructs a new <code>JredisConnectionFactory</code> instance. * Constructs a new <code>JredisConnectionFactory</code> instance.
*/ */
public JredisConnectionFactory() { public JredisConnectionFactory() {}
}
/** /**
* Constructs a new <code>JredisConnectionFactory</code> instance. * Constructs a new <code>JredisConnectionFactory</code> instance. Will override the other connection parameters
* Will override the other connection parameters passed to the factory. * passed to the factory.
* *
* @param connectionSpec already configured connection. * @param connectionSpec already configured connection.
*/ */
public JredisConnectionFactory(ConnectionSpec connectionSpec) { public JredisConnectionFactory(ConnectionSpec connectionSpec) {
this.connectionSpec = connectionSpec; this.connectionSpec = connectionSpec;
} }
public JredisConnectionFactory(Pool<JRedis> pool) { public JredisConnectionFactory(Pool<JRedis> pool) {
this.pool = pool; this.pool = pool;
} }
@@ -88,9 +86,9 @@ public class JredisConnectionFactory implements InitializingBean, DisposableBean
} }
} }
} }
public void destroy() throws Exception { public void destroy() throws Exception {
if(pool != null) { if (pool != null) {
pool.destroy(); pool.destroy();
pool = null; pool = null;
} }
@@ -98,18 +96,17 @@ public class JredisConnectionFactory implements InitializingBean, DisposableBean
public RedisConnection getConnection() { public RedisConnection getConnection() {
JredisConnection connection; JredisConnection connection;
if(pool != null) { if (pool != null) {
connection = new JredisConnection(pool.getResource(), pool); connection = new JredisConnection(pool.getResource(), pool);
}else { } else {
connection = new JredisConnection(new JRedisClient(connectionSpec), null); connection = new JredisConnection(new JRedisClient(connectionSpec), null);
} }
return postProcessConnection(connection); return postProcessConnection(connection);
} }
/** /**
* Post process a newly retrieved connection. Useful for decorating or executing * Post process a newly retrieved connection. Useful for decorating or executing initialization commands on a new
* initialization commands on a new connection. * connection. This implementation simply returns the connection.
* This implementation simply returns the connection.
* *
* @param connection * @param connection
* @return processed connection * @return processed connection
@@ -118,7 +115,6 @@ public class JredisConnectionFactory implements InitializingBean, DisposableBean
return connection; return connection;
} }
public DataAccessException translateExceptionIfPossible(RuntimeException ex) { public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
if (ex instanceof ClientRuntimeException) { if (ex instanceof ClientRuntimeException) {
return JredisUtils.convertJredisAccessException((ClientRuntimeException) ex); return JredisUtils.convertJredisAccessException((ClientRuntimeException) ex);
@@ -126,10 +122,9 @@ public class JredisConnectionFactory implements InitializingBean, DisposableBean
return null; return null;
} }
/** /**
* Returns the Redis host name of this factory. * Returns the Redis host name of this factory.
* *
* @return Returns the hostName * @return Returns the hostName
*/ */
public String getHostName() { public String getHostName() {
@@ -145,10 +140,9 @@ public class JredisConnectionFactory implements InitializingBean, DisposableBean
this.hostName = hostName; this.hostName = hostName;
} }
/** /**
* Returns the Redis port. * Returns the Redis port.
* *
* @return Returns the port * @return Returns the port
*/ */
public int getPort() { public int getPort() {
@@ -184,7 +178,7 @@ public class JredisConnectionFactory implements InitializingBean, DisposableBean
/** /**
* Returns the index of the database. * Returns the index of the database.
* *
* @return Returns the database index * @return Returns the database index
*/ */
public int getDatabase() { public int getDatabase() {
@@ -192,8 +186,7 @@ public class JredisConnectionFactory implements InitializingBean, DisposableBean
} }
/** /**
* Sets the index of the database used by this connection factory. * Sets the index of the database used by this connection factory. Can be between 0 (default) and 15.
* Can be between 0 (default) and 15.
* *
* @param index database index * @param index database index
*/ */
@@ -208,4 +201,4 @@ public class JredisConnectionFactory implements InitializingBean, DisposableBean
public boolean getConvertPipelineAndTxResults() { public boolean getConvertPipelineAndTxResults() {
return false; return false;
} }
} }

View File

@@ -32,59 +32,44 @@ import org.springframework.util.StringUtils;
* JRedis implementation of {@link Pool} * JRedis implementation of {@link Pool}
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
public class JredisPool implements Pool<JRedis> { public class JredisPool implements Pool<JRedis> {
private final GenericObjectPool internalPool; private final GenericObjectPool internalPool;
/** /**
* Uses the {@link Config} and {@link ConnectionSpec} defaults for * Uses the {@link Config} and {@link ConnectionSpec} defaults for configuring the connection pool
* configuring the connection pool *
* * @param hostName The Redis host
* @param hostName * @param port The Redis port
* The Redis host
* @param port
* The Redis port
*/ */
public JredisPool(String hostName, int port) { public JredisPool(String hostName, int port) {
this(hostName, port, 0, null, 0, new Config()); this(hostName, port, 0, null, 0, new Config());
} }
/** /**
* Uses the {@link ConnectionSpec} defaults for configuring the connection * Uses the {@link ConnectionSpec} defaults for configuring the connection pool
* pool
* *
* @param hostName * @param hostName The Redis host
* The Redis host * @param port The Redis port
* @param port * @param poolConfig The pool {@link Config}
* The Redis port
* @param poolConfig
* The pool {@link Config}
*/ */
public JredisPool(String hostName, int port, Config poolConfig) { public JredisPool(String hostName, int port, Config poolConfig) {
this(hostName, port, 0, null, 0, poolConfig); this(hostName, port, 0, null, 0, poolConfig);
} }
/** /**
*
* Uses the {@link Config} defaults for configuring the connection pool * Uses the {@link Config} defaults for configuring the connection pool
* *
* @param connectionSpec * @param connectionSpec The {@link ConnectionSpec} for connecting to Redis
* The {@link ConnectionSpec} for connecting to Redis
*
*/ */
public JredisPool(ConnectionSpec connectionSpec) { public JredisPool(ConnectionSpec connectionSpec) {
this.internalPool = new GenericObjectPool(new JredisFactory(connectionSpec), new Config()); this.internalPool = new GenericObjectPool(new JredisFactory(connectionSpec), new Config());
} }
/** /**
* * @param connectionSpec The {@link ConnectionSpec} for connecting to Redis
* @param connectionSpec * @param poolConfig The pool {@link Config}
* The {@link ConnectionSpec} for connecting to Redis
*
* @param poolConfig
* The pool {@link Config}
*/ */
public JredisPool(ConnectionSpec connectionSpec, Config poolConfig) { public JredisPool(ConnectionSpec connectionSpec, Config poolConfig) {
this.internalPool = new GenericObjectPool(new JredisFactory(connectionSpec), poolConfig); this.internalPool = new GenericObjectPool(new JredisFactory(connectionSpec), poolConfig);
@@ -92,45 +77,28 @@ public class JredisPool implements Pool<JRedis> {
/** /**
* Uses the {@link Config} defaults for configuring the connection pool * Uses the {@link Config} defaults for configuring the connection pool
* *
* @param hostName * @param hostName The Redis host
* The Redis host * @param port The Redis port
* @param port * @param dbIndex The index of the database all connections should use. The database will only be selected on initial
* The Redis port * creation of the pooled {@link JRedis} instances. Since calling select directly on {@link JRedis} is not
* @param dbIndex * supported, it is assumed that connections can be re-used without subsequent selects.
* The index of the database all connections should use. The * @param password The password used for authenticating with the Redis server or null if no password required
* database will only be selected on initial creation of the * @param timeout The socket timeout or 0 to use the default socket timeout
* pooled {@link JRedis} instances. Since calling select directly
* on {@link JRedis} is not supported, it is assumed that
* connections can be re-used without subsequent selects.
* @param password
* The password used for authenticating with the Redis server or
* null if no password required
* @param timeout
* The socket timeout or 0 to use the default socket timeout
*/ */
public JredisPool(String hostName, int port, int dbIndex, String password, int timeout) { public JredisPool(String hostName, int port, int dbIndex, String password, int timeout) {
this(hostName, port, dbIndex, password, timeout, new Config()); this(hostName, port, dbIndex, password, timeout, new Config());
} }
/** /**
* * @param hostName The Redis host
* @param hostName * @param port The Redis port
* The Redis host * @param dbIndex The index of the database all connections should use
* @param port * @param password The password used for authenticating with the Redis server or null if no password required
* The Redis port * @param timeout The socket timeout or 0 to use the default socket timeout
* @param dbIndex * @param poolConfig The pool {@link Config}
* The index of the database all connections should use
* @param password
* The password used for authenticating with the Redis server or
* null if no password required
* @param timeout
* The socket timeout or 0 to use the default socket timeout
* @param poolConfig
* The pool {@link Config}
*/ */
public JredisPool(String hostName, int port, int dbIndex, String password, int timeout, public JredisPool(String hostName, int port, int dbIndex, String password, int timeout, Config poolConfig) {
Config poolConfig) {
ConnectionSpec connectionSpec = DefaultConnectionSpec.newSpec(hostName, port, dbIndex, null); ConnectionSpec connectionSpec = DefaultConnectionSpec.newSpec(hostName, port, dbIndex, null);
connectionSpec.setConnectionFlag(Connection.Flag.RELIABLE, false); connectionSpec.setConnectionFlag(Connection.Flag.RELIABLE, false);
if (StringUtils.hasLength(password)) { if (StringUtils.hasLength(password)) {
@@ -191,7 +159,7 @@ public class JredisPool implements Pool<JRedis> {
if (obj instanceof JRedis) { if (obj instanceof JRedis) {
try { try {
((JRedis) obj).quit(); ((JRedis) obj).quit();
}catch(Exception e) { } catch (Exception e) {
// Errors may happen if returning a broken resource // Errors may happen if returning a broken resource
} }
} }

View File

@@ -34,7 +34,7 @@ import org.springframework.data.redis.connection.SortParameters.Order;
import org.springframework.data.redis.connection.SortParameters.Range; import org.springframework.data.redis.connection.SortParameters.Range;
/** /**
* Helper class featuring methods for JRedis connection handling, providing support for exception translation. * Helper class featuring methods for JRedis connection handling, providing support for exception translation.
* *
* @author Costin Leau * @author Costin Leau
* @author Jennifer Hickey * @author Jennifer Hickey
@@ -66,18 +66,18 @@ public abstract class JredisUtils {
static DataType convertDataType(RedisType type) { static DataType convertDataType(RedisType type) {
switch (type) { switch (type) {
case NONE: case NONE:
return DataType.NONE; return DataType.NONE;
case string: case string:
return DataType.STRING; return DataType.STRING;
case list: case list:
return DataType.LIST; return DataType.LIST;
case set: case set:
return DataType.SET; return DataType.SET;
//case zset: // case zset:
// return DataType.ZSET; // return DataType.ZSET;
case hash: case hash:
return DataType.HASH; return DataType.HASH;
} }
return null; return null;
@@ -114,7 +114,6 @@ public abstract class JredisUtils {
jredisSort.STORE(storeKey); jredisSort.STORE(storeKey);
} }
return jredisSort; return jredisSort;
} }
@@ -127,4 +126,4 @@ public abstract class JredisUtils {
static Long toLong(Boolean source) { static Long toLong(Boolean source) {
return source ? 1l : 0l; return source ? 1l : 0l;
} }
} }

View File

@@ -22,11 +22,9 @@ import com.lambdaworks.redis.codec.RedisCodec;
import com.lambdaworks.redis.pubsub.RedisPubSubConnection; import com.lambdaworks.redis.pubsub.RedisPubSubConnection;
/** /**
* Extension of {@link RedisClient} that calls auth on all new connections using * Extension of {@link RedisClient} that calls auth on all new connections using the supplied credentials
* the supplied credentials
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
public class AuthenticatingRedisClient extends RedisClient { public class AuthenticatingRedisClient extends RedisClient {

View File

@@ -31,7 +31,6 @@ import com.lambdaworks.redis.RedisClient;
* Default implementation of {@link LettucePool} * Default implementation of {@link LettucePool}
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
public class DefaultLettucePool implements LettucePool, InitializingBean { public class DefaultLettucePool implements LettucePool, InitializingBean {
private GenericObjectPool internalPool; private GenericObjectPool internalPool;
@@ -44,20 +43,15 @@ public class DefaultLettucePool implements LettucePool, InitializingBean {
private long timeout = TimeUnit.MILLISECONDS.convert(60, TimeUnit.SECONDS); private long timeout = TimeUnit.MILLISECONDS.convert(60, TimeUnit.SECONDS);
/** /**
* Constructs a new <code>DefaultLettucePool</code> instance with * Constructs a new <code>DefaultLettucePool</code> instance with default settings.
* default settings.
*/ */
public DefaultLettucePool() { public DefaultLettucePool() {}
}
/** /**
* Uses the {@link Config} and {@link RedisClient} defaults for configuring * Uses the {@link Config} and {@link RedisClient} defaults for configuring the connection pool
* the connection pool
* *
* @param hostName * @param hostName The Redis host
* The Redis host * @param port The Redis port
* @param port
* The Redis port
*/ */
public DefaultLettucePool(String hostName, int port) { public DefaultLettucePool(String hostName, int port) {
this.hostName = hostName; this.hostName = hostName;
@@ -67,12 +61,9 @@ public class DefaultLettucePool implements LettucePool, InitializingBean {
/** /**
* Uses the {@link RedisClient} defaults for configuring the connection pool * Uses the {@link RedisClient} defaults for configuring the connection pool
* *
* @param hostName * @param hostName The Redis host
* The Redis host * @param port The Redis port
* @param port * @param poolConfig The pool {@link Config}
* The Redis port
* @param poolConfig
* The pool {@link Config}
*/ */
public DefaultLettucePool(String hostName, int port, Config poolConfig) { public DefaultLettucePool(String hostName, int port, Config poolConfig) {
this.hostName = hostName; this.hostName = hostName;
@@ -81,8 +72,8 @@ public class DefaultLettucePool implements LettucePool, InitializingBean {
} }
public void afterPropertiesSet() { public void afterPropertiesSet() {
this.client = password != null ? new AuthenticatingRedisClient(hostName, port, password) : this.client = password != null ? new AuthenticatingRedisClient(hostName, port, password) : new RedisClient(
new RedisClient(hostName, port); hostName, port);
client.setDefaultTimeout(timeout, TimeUnit.MILLISECONDS); client.setDefaultTimeout(timeout, TimeUnit.MILLISECONDS);
this.internalPool = new GenericObjectPool(new LettuceFactory(client, dbIndex), poolConfig); this.internalPool = new GenericObjectPool(new LettuceFactory(client, dbIndex), poolConfig);
} }
@@ -126,7 +117,6 @@ public class DefaultLettucePool implements LettucePool, InitializingBean {
} }
/** /**
*
* @return The pool configuration * @return The pool configuration
*/ */
public Config getPoolConfig() { public Config getPoolConfig() {
@@ -134,7 +124,6 @@ public class DefaultLettucePool implements LettucePool, InitializingBean {
} }
/** /**
*
* @param poolConfig The pool configuration to use * @param poolConfig The pool configuration to use
*/ */
public void setPoolConfig(Config poolConfig) { public void setPoolConfig(Config poolConfig) {
@@ -143,7 +132,7 @@ public class DefaultLettucePool implements LettucePool, InitializingBean {
/** /**
* Returns the index of the database. * Returns the index of the database.
* *
* @return Returns the database index * @return Returns the database index
*/ */
public int getDatabase() { public int getDatabase() {
@@ -151,11 +140,9 @@ public class DefaultLettucePool implements LettucePool, InitializingBean {
} }
/** /**
* Sets the index of the database used by this connection pool. Default * Sets the index of the database used by this connection pool. Default is 0.
* is 0. *
* * @param index database index
* @param index
* database index
*/ */
public void setDatabase(int index) { public void setDatabase(int index) {
Assert.isTrue(index >= 0, "invalid DB index (a positive index required)"); Assert.isTrue(index >= 0, "invalid DB index (a positive index required)");
@@ -164,7 +151,7 @@ public class DefaultLettucePool implements LettucePool, InitializingBean {
/** /**
* Returns the password used for authenticating with the Redis server. * Returns the password used for authenticating with the Redis server.
* *
* @return password for authentication * @return password for authentication
*/ */
public String getPassword() { public String getPassword() {
@@ -173,7 +160,7 @@ public class DefaultLettucePool implements LettucePool, InitializingBean {
/** /**
* Sets the password used for authenticating with the Redis server. * Sets the password used for authenticating with the Redis server.
* *
* @param password the password to set * @param password the password to set
*/ */
public void setPassword(String password) { public void setPassword(String password) {
@@ -182,7 +169,7 @@ public class DefaultLettucePool implements LettucePool, InitializingBean {
/** /**
* Returns the current host. * Returns the current host.
* *
* @return the host * @return the host
*/ */
public String getHostName() { public String getHostName() {
@@ -191,9 +178,8 @@ public class DefaultLettucePool implements LettucePool, InitializingBean {
/** /**
* Sets the host. * Sets the host.
* *
* @param host * @param host the host to set
* the host to set
*/ */
public void setHostName(String host) { public void setHostName(String host) {
this.hostName = host; this.hostName = host;
@@ -201,7 +187,7 @@ public class DefaultLettucePool implements LettucePool, InitializingBean {
/** /**
* Returns the current port. * Returns the current port.
* *
* @return the port * @return the port
*/ */
public int getPort() { public int getPort() {
@@ -210,9 +196,8 @@ public class DefaultLettucePool implements LettucePool, InitializingBean {
/** /**
* Sets the port. * Sets the port.
* *
* @param port * @param port the port to set
* the port to set
*/ */
public void setPort(int port) { public void setPort(int port) {
this.port = port; this.port = port;
@@ -220,7 +205,7 @@ public class DefaultLettucePool implements LettucePool, InitializingBean {
/** /**
* Returns the connection timeout (in milliseconds). * Returns the connection timeout (in milliseconds).
* *
* @return connection timeout * @return connection timeout
*/ */
public long getTimeout() { public long getTimeout() {
@@ -229,9 +214,8 @@ public class DefaultLettucePool implements LettucePool, InitializingBean {
/** /**
* Sets the connection timeout (in milliseconds). * Sets the connection timeout (in milliseconds).
* *
* @param timeout * @param timeout connection timeout
* connection timeout
*/ */
public void setTimeout(long timeout) { public void setTimeout(long timeout) {
this.timeout = timeout; this.timeout = timeout;

View File

@@ -34,28 +34,21 @@ import com.lambdaworks.redis.RedisClient;
import com.lambdaworks.redis.RedisException; import com.lambdaworks.redis.RedisException;
/** /**
* Connection factory creating <a * Connection factory creating <a href="http://github.com/wg/lettuce">Lettuce</a>-based connections.
* href="http://github.com/wg/lettuce">Lettuce</a>-based connections.
* <p> * <p>
* This factory creates a new {@link LettuceConnection} on each call to * This factory creates a new {@link LettuceConnection} on each call to {@link #getConnection()}. Multiple
* {@link #getConnection()}. Multiple {@link LettuceConnection}s share a single * {@link LettuceConnection}s share a single thread-safe native connection by default.
* thread-safe native connection by default.
*
* <p> * <p>
* The shared native connection is never closed by {@link LettuceConnection}, * The shared native connection is never closed by {@link LettuceConnection}, therefore it is not validated by default
* therefore it is not validated by default on {@link #getConnection()}. Use * on {@link #getConnection()}. Use {@link #setValidateConnection(boolean)} to change this behavior if necessary. Inject
* {@link #setValidateConnection(boolean)} to change this behavior if necessary. * a {@link Pool} to pool dedicated connections. If shareNativeConnection is true, the pool will be used to select a
* * connection for blocking and tx operations only, which should not share a connection. If native connection sharing is
* Inject a {@link Pool} to pool dedicated connections. If shareNativeConnection is * disabled, the selected connection will be used for all operations.
* true, the pool will be used to select a connection for blocking and tx operations only, *
* which should not share a connection. If native connection sharing is disabled,
* the selected connection will be used for all operations.
*
* @author Costin Leau * @author Costin Leau
* @author Jennifer Hickey * @author Jennifer Hickey
*/ */
public class LettuceConnectionFactory implements InitializingBean, DisposableBean, public class LettuceConnectionFactory implements InitializingBean, DisposableBean, RedisConnectionFactory {
RedisConnectionFactory {
private final Log log = LogFactory.getLog(getClass()); private final Log log = LogFactory.getLog(getClass());
@@ -74,15 +67,12 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
private boolean convertPipelineAndTxResults = true; private boolean convertPipelineAndTxResults = true;
/** /**
* Constructs a new <code>LettuceConnectionFactory</code> instance with * Constructs a new <code>LettuceConnectionFactory</code> instance with default settings.
* default settings.
*/ */
public LettuceConnectionFactory() { public LettuceConnectionFactory() {}
}
/** /**
* Constructs a new <code>LettuceConnectionFactory</code> instance with * Constructs a new <code>LettuceConnectionFactory</code> instance with default settings.
* default settings.
*/ */
public LettuceConnectionFactory(String host, int port) { public LettuceConnectionFactory(String host, int port) {
this.hostName = host; this.hostName = host;
@@ -118,12 +108,11 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
} }
/** /**
* Reset the underlying shared Connection, to be reinitialized on next * Reset the underlying shared Connection, to be reinitialized on next access.
* access.
*/ */
public void resetConnection() { public void resetConnection() {
synchronized (this.connectionMonitor) { synchronized (this.connectionMonitor) {
if(this.connection != null) { if (this.connection != null) {
this.connection.close(); this.connection.close();
} }
this.connection = null; this.connection = null;
@@ -150,7 +139,7 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
/** /**
* Returns the current host. * Returns the current host.
* *
* @return the host * @return the host
*/ */
public String getHostName() { public String getHostName() {
@@ -159,9 +148,8 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
/** /**
* Sets the host. * Sets the host.
* *
* @param host * @param host the host to set
* the host to set
*/ */
public void setHostName(String host) { public void setHostName(String host) {
this.hostName = host; this.hostName = host;
@@ -169,7 +157,7 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
/** /**
* Returns the current port. * Returns the current port.
* *
* @return the port * @return the port
*/ */
public int getPort() { public int getPort() {
@@ -178,9 +166,8 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
/** /**
* Sets the port. * Sets the port.
* *
* @param port * @param port the port to set
* the port to set
*/ */
public void setPort(int port) { public void setPort(int port) {
this.port = port; this.port = port;
@@ -188,7 +175,7 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
/** /**
* Returns the connection timeout (in milliseconds). * Returns the connection timeout (in milliseconds).
* *
* @return connection timeout * @return connection timeout
*/ */
public long getTimeout() { public long getTimeout() {
@@ -197,9 +184,8 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
/** /**
* Sets the connection timeout (in milliseconds). * Sets the connection timeout (in milliseconds).
* *
* @param timeout * @param timeout connection timeout
* connection timeout
*/ */
public void setTimeout(long timeout) { public void setTimeout(long timeout) {
this.timeout = timeout; this.timeout = timeout;
@@ -207,7 +193,7 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
/** /**
* Indicates if validation of the native Lettuce connection is enabled * Indicates if validation of the native Lettuce connection is enabled
* *
* @return connection validation enabled * @return connection validation enabled
*/ */
public boolean getValidateConnection() { public boolean getValidateConnection() {
@@ -215,30 +201,25 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
} }
/** /**
* Enables validation of the shared native Lettuce connection on calls to * Enables validation of the shared native Lettuce connection on calls to {@link #getConnection()}. A new connection
* {@link #getConnection()}. A new connection will be created and used if * will be created and used if validation fails.
* validation fails.
* <p> * <p>
* Lettuce will automatically reconnect until close is called, which should * Lettuce will automatically reconnect until close is called, which should never happen through
* never happen through {@link LettuceConnection} if a shared native * {@link LettuceConnection} if a shared native connection is used, therefore the default is false.
* connection is used, therefore the default is false.
* <p> * <p>
* Setting this to true will result in a round-trip call to the server on * Setting this to true will result in a round-trip call to the server on each new connection, so this setting should
* each new connection, so this setting should only be used if connection * only be used if connection sharing is enabled and there is code that is actively closing the native Lettuce
* sharing is enabled and there is code that is actively closing the native * connection.
* Lettuce connection. *
* * @param validateConnection enable connection validation
* @param validateConnection
* enable connection validation
*/ */
public void setValidateConnection(boolean validateConnection) { public void setValidateConnection(boolean validateConnection) {
this.validateConnection = validateConnection; this.validateConnection = validateConnection;
} }
/** /**
* Indicates if multiple {@link LettuceConnection}s should share a single * Indicates if multiple {@link LettuceConnection}s should share a single native connection.
* native connection. *
*
* @return native connection shared * @return native connection shared
*/ */
public boolean getShareNativeConnection() { public boolean getShareNativeConnection() {
@@ -246,12 +227,10 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
} }
/** /**
* Enables multiple {@link LettuceConnection}s to share a single native * Enables multiple {@link LettuceConnection}s to share a single native connection. If set to false, every operation
* connection. If set to false, every operation on {@link LettuceConnection} * on {@link LettuceConnection} will open and close a socket.
* will open and close a socket. *
* * @param shareNativeConnection enable connection sharing
* @param shareNativeConnection
* enable connection sharing
*/ */
public void setShareNativeConnection(boolean shareNativeConnection) { public void setShareNativeConnection(boolean shareNativeConnection) {
this.shareNativeConnection = shareNativeConnection; this.shareNativeConnection = shareNativeConnection;
@@ -259,7 +238,7 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
/** /**
* Returns the index of the database. * Returns the index of the database.
* *
* @return Returns the database index * @return Returns the database index
*/ */
public int getDatabase() { public int getDatabase() {
@@ -267,11 +246,9 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
} }
/** /**
* Sets the index of the database used by this connection factory. Default * Sets the index of the database used by this connection factory. Default is 0.
* is 0. *
* * @param index database index
* @param index
* database index
*/ */
public void setDatabase(int index) { public void setDatabase(int index) {
Assert.isTrue(index >= 0, "invalid DB index (a positive index required)"); Assert.isTrue(index >= 0, "invalid DB index (a positive index required)");
@@ -280,7 +257,7 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
/** /**
* Returns the password used for authenticating with the Redis server. * Returns the password used for authenticating with the Redis server.
* *
* @return password for authentication * @return password for authentication
*/ */
public String getPassword() { public String getPassword() {
@@ -289,7 +266,7 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
/** /**
* Sets the password used for authenticating with the Redis server. * Sets the password used for authenticating with the Redis server.
* *
* @param password the password to set * @param password the password to set
*/ */
public void setPassword(String password) { public void setPassword(String password) {
@@ -297,10 +274,10 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
} }
/** /**
* Specifies if pipelined results should be converted to the expected data * Specifies if pipelined results should be converted to the expected data type. If false, results of
* type. If false, results of {@link LettuceConnection#closePipeline()} and {LettuceConnection#exec()} * {@link LettuceConnection#closePipeline()} and {LettuceConnection#exec()} will be of the type returned by the
* will be of the type returned by the Lettuce driver * Lettuce driver
* *
* @return Whether or not to convert pipeline and tx results * @return Whether or not to convert pipeline and tx results
*/ */
public boolean getConvertPipelineAndTxResults() { public boolean getConvertPipelineAndTxResults() {
@@ -308,10 +285,10 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
} }
/** /**
* Specifies if pipelined and transaction results should be converted to the expected data * Specifies if pipelined and transaction results should be converted to the expected data type. If false, results of
* type. If false, results of {@link LettuceConnection#closePipeline()} and {LettuceConnection#exec()} * {@link LettuceConnection#closePipeline()} and {LettuceConnection#exec()} will be of the type returned by the
* will be of the type returned by the Lettuce driver * Lettuce driver
* *
* @param convertPipelineAndTxResults Whether or not to convert pipeline and tx results * @param convertPipelineAndTxResults Whether or not to convert pipeline and tx results
*/ */
public void setConvertPipelineAndTxResults(boolean convertPipelineAndTxResults) { public void setConvertPipelineAndTxResults(boolean convertPipelineAndTxResults) {
@@ -337,23 +314,22 @@ public class LettuceConnectionFactory implements InitializingBean, DisposableBea
protected RedisAsyncConnection<byte[], byte[]> createLettuceConnector() { protected RedisAsyncConnection<byte[], byte[]> createLettuceConnector() {
try { try {
RedisAsyncConnection<byte[], byte[]> connection = client.connectAsync(LettuceConnection.CODEC); RedisAsyncConnection<byte[], byte[]> connection = client.connectAsync(LettuceConnection.CODEC);
if(dbIndex > 0) { if (dbIndex > 0) {
connection.select(dbIndex); connection.select(dbIndex);
} }
return connection; return connection;
} catch (RedisException e) { } catch (RedisException e) {
throw new RedisConnectionFailureException("Unable to connect to Redis on " + throw new RedisConnectionFailureException("Unable to connect to Redis on " + getHostName() + ":" + getPort(), e);
getHostName() + ":" + getPort(), e);
} }
} }
private RedisClient createRedisClient() { private RedisClient createRedisClient() {
if(pool != null) { if (pool != null) {
return pool.getClient(); return pool.getClient();
} }
RedisClient client = password != null ? new AuthenticatingRedisClient(hostName, port, password) : RedisClient client = password != null ? new AuthenticatingRedisClient(hostName, port, password) : new RedisClient(
new RedisClient(hostName, port); hostName, port);
client.setDefaultTimeout(timeout, TimeUnit.MILLISECONDS); client.setDefaultTimeout(timeout, TimeUnit.MILLISECONDS);
return client; return client;
} }
} }

View File

@@ -40,9 +40,8 @@ import com.lambdaworks.redis.protocol.Charsets;
/** /**
* Lettuce type converters * Lettuce type converters
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
abstract public class LettuceConverters extends Converters { abstract public class LettuceConverters extends Converters {
@@ -161,19 +160,18 @@ abstract public class LettuceConverters extends Converters {
public static ScriptOutputType toScriptOutputType(ReturnType returnType) { public static ScriptOutputType toScriptOutputType(ReturnType returnType) {
switch (returnType) { switch (returnType) {
case BOOLEAN: case BOOLEAN:
return ScriptOutputType.BOOLEAN; return ScriptOutputType.BOOLEAN;
case MULTI: case MULTI:
return ScriptOutputType.MULTI; return ScriptOutputType.MULTI;
case VALUE: case VALUE:
return ScriptOutputType.VALUE; return ScriptOutputType.VALUE;
case INTEGER: case INTEGER:
return ScriptOutputType.INTEGER; return ScriptOutputType.INTEGER;
case STATUS: case STATUS:
return ScriptOutputType.STATUS; return ScriptOutputType.STATUS;
default: default:
throw new IllegalArgumentException("Return type " + returnType throw new IllegalArgumentException("Return type " + returnType + " is not a supported script output type");
+ " is not a supported script output type");
} }
} }

View File

@@ -29,9 +29,8 @@ import com.lambdaworks.redis.RedisException;
/** /**
* Converts Lettuce Exceptions to {@link DataAccessException}s * Converts Lettuce Exceptions to {@link DataAccessException}s
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
public class LettuceExceptionConverter implements Converter<Exception, DataAccessException> { public class LettuceExceptionConverter implements Converter<Exception, DataAccessException> {

View File

@@ -44,15 +44,11 @@ class LettuceMessageListener implements RedisPubSubListener<byte[], byte[]> {
listener.onMessage(new DefaultMessage(channel, message), pattern); listener.onMessage(new DefaultMessage(channel, message), pattern);
} }
public void subscribed(byte[] channel, long count) { public void subscribed(byte[] channel, long count) {}
}
public void psubscribed(byte[] pattern, long count) { public void psubscribed(byte[] pattern, long count) {}
}
public void unsubscribed(byte[] channel, long count) { public void unsubscribed(byte[] channel, long count) {}
}
public void punsubscribed(byte[] pattern, long count) { public void punsubscribed(byte[] pattern, long count) {}
}
} }

View File

@@ -22,16 +22,13 @@ import com.lambdaworks.redis.RedisAsyncConnection;
import com.lambdaworks.redis.RedisClient; import com.lambdaworks.redis.RedisClient;
/** /**
*
* Pool of Lettuce {@link RedisAsyncConnection}s * Pool of Lettuce {@link RedisAsyncConnection}s
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
public interface LettucePool extends Pool<RedisAsyncConnection<byte[], byte[]>> { public interface LettucePool extends Pool<RedisAsyncConnection<byte[], byte[]>> {
/** /**
*
* @return The {@link RedisClient} used to create pooled connections * @return The {@link RedisClient} used to create pooled connections
*/ */
RedisClient getClient(); RedisClient getClient();

View File

@@ -40,17 +40,16 @@ class LettuceSubscription extends AbstractSubscription {
} }
protected void doClose() { protected void doClose() {
if(!getChannels().isEmpty()) { if (!getChannels().isEmpty()) {
pubsub.unsubscribe(new byte[0]); pubsub.unsubscribe(new byte[0]);
} }
if(!getPatterns().isEmpty()) { if (!getPatterns().isEmpty()) {
pubsub.punsubscribe(new byte[0]); pubsub.punsubscribe(new byte[0]);
} }
pubsub.removeListener(this.listener); pubsub.removeListener(this.listener);
pubsub.close(); pubsub.close();
} }
protected void doPsubscribe(byte[]... patterns) { protected void doPsubscribe(byte[]... patterns) {
pubsub.psubscribe(patterns); pubsub.psubscribe(patterns);
} }
@@ -68,4 +67,4 @@ class LettuceSubscription extends AbstractSubscription {
// lettuce doesn't automatically subscribe from all patterns // lettuce doesn't automatically subscribe from all patterns
pubsub.unsubscribe(channels); pubsub.unsubscribe(channels);
} }
} }

View File

@@ -46,10 +46,9 @@ import com.lambdaworks.redis.codec.RedisCodec;
import com.lambdaworks.redis.protocol.Charsets; import com.lambdaworks.redis.protocol.Charsets;
/** /**
* Helper class featuring methods for Lettuce connection handling, providing * Helper class featuring methods for Lettuce connection handling, providing support for exception translation.
* support for exception translation.
*
* Deprecated in favor of {@link LettuceConverters} * Deprecated in favor of {@link LettuceConverters}
*
* @author Costin Leau * @author Costin Leau
*/ */
@Deprecated @Deprecated
@@ -68,7 +67,7 @@ abstract class LettuceUtils {
} }
static Properties info(String reply) { static Properties info(String reply) {
if(reply == null) { if (reply == null) {
return null; return null;
} }
Properties info = new Properties(); Properties info = new Properties();
@@ -93,7 +92,7 @@ abstract class LettuceUtils {
} }
static Set<Tuple> convertTuple(List<ScoredValue<byte[]>> zrange) { static Set<Tuple> convertTuple(List<ScoredValue<byte[]>> zrange) {
if(zrange == null) { if (zrange == null) {
return null; return null;
} }
Set<Tuple> tuples = new LinkedHashSet<Tuple>(zrange.size()); Set<Tuple> tuples = new LinkedHashSet<Tuple>(zrange.size());
@@ -107,7 +106,7 @@ abstract class LettuceUtils {
static SortArgs sort(SortParameters params) { static SortArgs sort(SortParameters params) {
SortArgs args = new SortArgs(); SortArgs args = new SortArgs();
if(params == null) { if (params == null) {
return args; return args;
} }
@@ -129,8 +128,7 @@ abstract class LettuceUtils {
if (params.getOrder() != null) { if (params.getOrder() != null) {
if (params.getOrder() == Order.ASC) { if (params.getOrder() == Order.ASC) {
args.asc(); args.asc();
} } else {
else {
args.desc(); args.desc();
} }
} }
@@ -147,15 +145,15 @@ abstract class LettuceUtils {
if (aggregate != null) { if (aggregate != null) {
switch (aggregate) { switch (aggregate) {
case MIN: case MIN:
args.min(); args.min();
break; break;
case MAX: case MAX:
args.max(); args.max();
break; break;
default: default:
args.sum(); args.sum();
break; break;
} }
} }
@@ -168,7 +166,7 @@ abstract class LettuceUtils {
} }
static List<byte[]> toList(KeyValue<byte[], byte[]> blpop) { static List<byte[]> toList(KeyValue<byte[], byte[]> blpop) {
if(blpop == null) { if (blpop == null) {
return null; return null;
} }
List<byte[]> list = new ArrayList<byte[]>(2); List<byte[]> list = new ArrayList<byte[]>(2);
@@ -179,34 +177,33 @@ abstract class LettuceUtils {
static ScriptOutputType toScriptOutputType(ReturnType returnType) { static ScriptOutputType toScriptOutputType(ReturnType returnType) {
switch (returnType) { switch (returnType) {
case BOOLEAN: case BOOLEAN:
return ScriptOutputType.BOOLEAN; return ScriptOutputType.BOOLEAN;
case MULTI: case MULTI:
return ScriptOutputType.MULTI; return ScriptOutputType.MULTI;
case VALUE: case VALUE:
return ScriptOutputType.VALUE; return ScriptOutputType.VALUE;
case INTEGER: case INTEGER:
return ScriptOutputType.INTEGER; return ScriptOutputType.INTEGER;
case STATUS: case STATUS:
return ScriptOutputType.STATUS; return ScriptOutputType.STATUS;
default: default:
throw new IllegalArgumentException("Return type " + returnType throw new IllegalArgumentException("Return type " + returnType + " is not a supported script output type");
+ " is not a supported script output type");
} }
} }
static byte[][] extractScriptKeys(int numKeys, byte[]... keysAndArgs) { static byte[][] extractScriptKeys(int numKeys, byte[]... keysAndArgs) {
if(numKeys > 0) { if (numKeys > 0) {
return Arrays.copyOfRange(keysAndArgs, 0,numKeys); return Arrays.copyOfRange(keysAndArgs, 0, numKeys);
} }
return new byte[0][0]; return new byte[0][0];
} }
static byte[][] extractScriptArgs(int numKeys, byte[]... keysAndArgs) { static byte[][] extractScriptArgs(int numKeys, byte[]... keysAndArgs) {
if(keysAndArgs.length > numKeys) { if (keysAndArgs.length > numKeys) {
return Arrays.copyOfRange(keysAndArgs, numKeys, keysAndArgs.length); return Arrays.copyOfRange(keysAndArgs, numKeys, keysAndArgs.length);
} }
return new byte[0][0]; return new byte[0][0];
} }
} }

View File

@@ -37,26 +37,21 @@ public class SrpConnectionFactory implements InitializingBean, DisposableBean, R
private BlockingQueue<SrpConnection> trackedConnections = new ArrayBlockingQueue<SrpConnection>(50); private BlockingQueue<SrpConnection> trackedConnections = new ArrayBlockingQueue<SrpConnection>(50);
private boolean convertPipelineAndTxResults = true; private boolean convertPipelineAndTxResults = true;
private String password; private String password;
/** /**
* Constructs a new <code>SRedisConnectionFactory</code> instance * Constructs a new <code>SRedisConnectionFactory</code> instance with default settings.
* with default settings.
*/ */
public SrpConnectionFactory() { public SrpConnectionFactory() {}
}
/** /**
* Constructs a new <code>SRedisConnectionFactory</code> instance * Constructs a new <code>SRedisConnectionFactory</code> instance with default settings.
* with default settings.
*/ */
public SrpConnectionFactory(String host, int port) { public SrpConnectionFactory(String host, int port) {
this.hostName = host; this.hostName = host;
this.port = port; this.port = port;
} }
public void afterPropertiesSet() { public void afterPropertiesSet() {}
}
public void destroy() { public void destroy() {
SrpConnection con; SrpConnection con;
@@ -73,8 +68,8 @@ public class SrpConnectionFactory implements InitializingBean, DisposableBean, R
} }
public RedisConnection getConnection() { public RedisConnection getConnection() {
SrpConnection connection = password != null ? new SrpConnection(hostName, port, password, trackedConnections) : SrpConnection connection = password != null ? new SrpConnection(hostName, port, password, trackedConnections)
new SrpConnection(hostName, port, trackedConnections); : new SrpConnection(hostName, port, trackedConnections);
connection.setConvertPipelineAndTxResults(convertPipelineAndTxResults); connection.setConvertPipelineAndTxResults(convertPipelineAndTxResults);
return connection; return connection;
} }
@@ -85,7 +80,7 @@ public class SrpConnectionFactory implements InitializingBean, DisposableBean, R
/** /**
* Returns the current host. * Returns the current host.
* *
* @return the host * @return the host
*/ */
public String getHostName() { public String getHostName() {
@@ -94,7 +89,7 @@ public class SrpConnectionFactory implements InitializingBean, DisposableBean, R
/** /**
* Sets the host. * Sets the host.
* *
* @param host the host to set * @param host the host to set
*/ */
public void setHostName(String host) { public void setHostName(String host) {
@@ -103,7 +98,7 @@ public class SrpConnectionFactory implements InitializingBean, DisposableBean, R
/** /**
* Returns the current port. * Returns the current port.
* *
* @return the port * @return the port
*/ */
public int getPort() { public int getPort() {
@@ -112,7 +107,7 @@ public class SrpConnectionFactory implements InitializingBean, DisposableBean, R
/** /**
* Sets the port. * Sets the port.
* *
* @param port the port to set * @param port the port to set
*/ */
public void setPort(int port) { public void setPort(int port) {
@@ -121,7 +116,7 @@ public class SrpConnectionFactory implements InitializingBean, DisposableBean, R
/** /**
* Returns the password used for authenticating with the Redis server. * Returns the password used for authenticating with the Redis server.
* *
* @return password for authentication * @return password for authentication
*/ */
public String getPassword() { public String getPassword() {
@@ -130,7 +125,7 @@ public class SrpConnectionFactory implements InitializingBean, DisposableBean, R
/** /**
* Sets the password used for authenticating with the Redis server. * Sets the password used for authenticating with the Redis server.
* *
* @param password the password to set * @param password the password to set
*/ */
public void setPassword(String password) { public void setPassword(String password) {
@@ -138,10 +133,10 @@ public class SrpConnectionFactory implements InitializingBean, DisposableBean, R
} }
/** /**
* Specifies if pipelined results should be converted to the expected data * Specifies if pipelined results should be converted to the expected data type. If false, results of
* type. If false, results of {@link SrpConnection#closePipeline()} and {@link SrpConnection#exec()} * {@link SrpConnection#closePipeline()} and {@link SrpConnection#exec()} will be of the type returned by the SRP
* will be of the type returned by the SRP driver * driver
* *
* @return Whether or not to convert pipeline and tx results * @return Whether or not to convert pipeline and tx results
*/ */
public boolean getConvertPipelineAndTxResults() { public boolean getConvertPipelineAndTxResults() {
@@ -149,13 +144,13 @@ public class SrpConnectionFactory implements InitializingBean, DisposableBean, R
} }
/** /**
* Specifies if pipelined results should be converted to the expected data * Specifies if pipelined results should be converted to the expected data type. If false, results of
* type. If false, results of {@link SrpConnection#closePipeline()} and {@link SrpConnection#exec()} * {@link SrpConnection#closePipeline()} and {@link SrpConnection#exec()} will be of the type returned by the SRP
* will be of the type returned by the SRP driver * driver
* *
* @param convertPipelineAndTxResults Whether or not to convert pipeline and tx results * @param convertPipelineAndTxResults Whether or not to convert pipeline and tx results
*/ */
public void setConvertPipelineAndTxResults(boolean convertPipelineAndTxResults) { public void setConvertPipelineAndTxResults(boolean convertPipelineAndTxResults) {
this.convertPipelineAndTxResults = convertPipelineAndTxResults; this.convertPipelineAndTxResults = convertPipelineAndTxResults;
} }
} }

View File

@@ -44,9 +44,8 @@ import com.google.common.base.Charsets;
/** /**
* SRP type converters * SRP type converters
* *
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
abstract public class SrpConverters extends Converters { abstract public class SrpConverters extends Converters {
@@ -77,8 +76,7 @@ abstract public class SrpConverters extends Converters {
} else if (data instanceof byte[]) } else if (data instanceof byte[])
list.add((byte[]) data); list.add((byte[]) data);
else else
throw new IllegalArgumentException( throw new IllegalArgumentException("array contains more then just nulls and bytes -> " + data);
"array contains more then just nulls and bytes -> " + data);
} }
return list; return list;
} }
@@ -95,13 +93,12 @@ abstract public class SrpConverters extends Converters {
}; };
BYTES_TO_DOUBLE = new Converter<byte[], Double>() { BYTES_TO_DOUBLE = new Converter<byte[], Double>() {
public Double convert(byte[] bytes) { public Double convert(byte[] bytes) {
return (bytes == null || bytes.length == 0 ? null : Double.valueOf(new String( return (bytes == null || bytes.length == 0 ? null : Double.valueOf(new String(bytes, Charsets.UTF_8)));
bytes, Charsets.UTF_8)));
} }
}; };
REPLIES_TO_TUPLE_SET = new Converter<Reply[], Set<Tuple>>() { REPLIES_TO_TUPLE_SET = new Converter<Reply[], Set<Tuple>>() {
public Set<Tuple> convert(Reply[] byteArrays) { public Set<Tuple> convert(Reply[] byteArrays) {
if(byteArrays == null) { if (byteArrays == null) {
return null; return null;
} }
Set<Tuple> tuples = new LinkedHashSet<Tuple>(byteArrays.length / 2 + 1); Set<Tuple> tuples = new LinkedHashSet<Tuple>(byteArrays.length / 2 + 1);
@@ -116,7 +113,7 @@ abstract public class SrpConverters extends Converters {
}; };
REPLIES_TO_BYTES_MAP = new Converter<Reply[], Map<byte[], byte[]>>() { REPLIES_TO_BYTES_MAP = new Converter<Reply[], Map<byte[], byte[]>>() {
public Map<byte[], byte[]> convert(Reply[] byteArrays) { public Map<byte[], byte[]> convert(Reply[] byteArrays) {
if(byteArrays == null) { if (byteArrays == null) {
return null; return null;
} }
Map<byte[], byte[]> map = new LinkedHashMap<byte[], byte[]>(byteArrays.length / 2); Map<byte[], byte[]> map = new LinkedHashMap<byte[], byte[]>(byteArrays.length / 2);
@@ -133,7 +130,7 @@ abstract public class SrpConverters extends Converters {
}; };
REPLIES_TO_BOOLEAN_LIST = new Converter<Reply[], List<Boolean>>() { REPLIES_TO_BOOLEAN_LIST = new Converter<Reply[], List<Boolean>>() {
public List<Boolean> convert(Reply[] source) { public List<Boolean> convert(Reply[] source) {
if(source == null) { if (source == null) {
return null; return null;
} }
List<Boolean> results = new ArrayList<Boolean>(); List<Boolean> results = new ArrayList<Boolean>();
@@ -145,7 +142,7 @@ abstract public class SrpConverters extends Converters {
}; };
REPLIES_TO_STRING_LIST = new Converter<Reply[], List<String>>() { REPLIES_TO_STRING_LIST = new Converter<Reply[], List<String>>() {
public List<String> convert(Reply[] source) { public List<String> convert(Reply[] source) {
if(source == null) { if (source == null) {
return null; return null;
} }
List<String> results = new ArrayList<String>(); List<String> results = new ArrayList<String>();

View File

@@ -44,15 +44,11 @@ class SrpMessageListener implements ReplyListener {
listener.onMessage(new DefaultMessage(channel, message), pattern); listener.onMessage(new DefaultMessage(channel, message), pattern);
} }
public void psubscribed(byte[] arg0, int arg1) { public void psubscribed(byte[] arg0, int arg1) {}
}
public void punsubscribed(byte[] arg0, int arg1) { public void punsubscribed(byte[] arg0, int arg1) {}
}
public void subscribed(byte[] arg0, int arg1) { public void subscribed(byte[] arg0, int arg1) {}
}
public void unsubscribed(byte[] arg0, int arg1) { public void unsubscribed(byte[] arg0, int arg1) {}
}
} }

View File

@@ -24,11 +24,9 @@ import org.springframework.data.redis.connection.ReturnType;
import redis.reply.Reply; import redis.reply.Reply;
/** /**
* Converts the value returned by SRP script eval to the expected * Converts the value returned by SRP script eval to the expected {@link ReturnType}
* {@link ReturnType} *
*
* @author Jennifer Hickey * @author Jennifer Hickey
*
*/ */
public class SrpScriptReturnConverter implements Converter<Object, Object> { public class SrpScriptReturnConverter implements Converter<Object, Object> {

View File

@@ -40,16 +40,15 @@ class SrpSubscription extends AbstractSubscription {
} }
protected void doClose() { protected void doClose() {
if(!getChannels().isEmpty()) { if (!getChannels().isEmpty()) {
client.unsubscribe((Object[]) null); client.unsubscribe((Object[]) null);
} }
if(!getPatterns().isEmpty()) { if (!getPatterns().isEmpty()) {
client.punsubscribe((Object[]) null); client.punsubscribe((Object[]) null);
} }
client.removeListener(this.listener); client.removeListener(this.listener);
} }
protected void doPsubscribe(byte[]... patterns) { protected void doPsubscribe(byte[]... patterns) {
client.psubscribe((Object[]) patterns); client.psubscribe((Object[]) patterns);
} }
@@ -57,8 +56,7 @@ class SrpSubscription extends AbstractSubscription {
protected void doPUnsubscribe(boolean all, byte[]... patterns) { protected void doPUnsubscribe(boolean all, byte[]... patterns) {
if (all) { if (all) {
client.punsubscribe((Object[]) null); client.punsubscribe((Object[]) null);
} } else {
else {
client.punsubscribe((Object[]) patterns); client.punsubscribe((Object[]) patterns);
} }
} }
@@ -70,9 +68,8 @@ class SrpSubscription extends AbstractSubscription {
protected void doUnsubscribe(boolean all, byte[]... channels) { protected void doUnsubscribe(boolean all, byte[]... channels) {
if (all) { if (all) {
client.unsubscribe((Object[]) null); client.unsubscribe((Object[]) null);
} } else {
else {
client.unsubscribe((Object[]) channels); client.unsubscribe((Object[]) channels);
} }
} }
} }

View File

@@ -48,9 +48,8 @@ import com.google.common.base.Charsets;
/** /**
* Helper class featuring methods for SRedis connection handling, providing support for exception translation. * Helper class featuring methods for SRedis connection handling, providing support for exception translation.
*
* Deprecated. Use {@link SrpConverters} instead. * Deprecated. Use {@link SrpConverters} instead.
* *
* @author Costin Leau * @author Costin Leau
* @author Jennifer Hickey * @author Jennifer Hickey
*/ */
@@ -68,7 +67,6 @@ abstract class SrpUtils {
private static final byte[] ALPHA = "ALPHA".getBytes(Charsets.UTF_8); private static final byte[] ALPHA = "ALPHA".getBytes(Charsets.UTF_8);
private static final byte[] STORE = "STORE".getBytes(Charsets.UTF_8); private static final byte[] STORE = "STORE".getBytes(Charsets.UTF_8);
static DataAccessException convertSRedisAccessException(RuntimeException ex) { static DataAccessException convertSRedisAccessException(RuntimeException ex) {
if (ex instanceof RedisException) { if (ex instanceof RedisException) {
return new RedisSystemException("redis exception", ex); return new RedisSystemException("redis exception", ex);
@@ -92,7 +90,7 @@ abstract class SrpUtils {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
static List<byte[]> toBytesList(Reply[] replies) { static List<byte[]> toBytesList(Reply[] replies) {
if(replies == null) { if (replies == null) {
return null; return null;
} }
List<byte[]> list = new ArrayList<byte[]>(replies.length); List<byte[]> list = new ArrayList<byte[]>(replies.length);
@@ -100,8 +98,7 @@ abstract class SrpUtils {
Object data = reply.data(); Object data = reply.data();
if (data == null) { if (data == null) {
list.add(null); list.add(null);
} } else if (data instanceof byte[])
else if (data instanceof byte[])
list.add((byte[]) data); list.add((byte[]) data);
else else
throw new IllegalArgumentException("array contains more then just nulls and bytes -> " + data); throw new IllegalArgumentException("array contains more then just nulls and bytes -> " + data);
@@ -112,8 +109,8 @@ abstract class SrpUtils {
static List<String> asStatusList(Reply[] replies) { static List<String> asStatusList(Reply[] replies) {
List<String> statuses = new ArrayList<String>(); List<String> statuses = new ArrayList<String>();
for(Reply reply: replies) { for (Reply reply : replies) {
statuses.add(((StatusReply)reply).data()); statuses.add(((StatusReply) reply).data());
} }
return statuses; return statuses;
} }
@@ -182,7 +179,7 @@ abstract class SrpUtils {
args[i] = keys[i]; args[i] = keys[i];
} }
} }
args[length-1] = String.valueOf(timeout).getBytes(); args[length - 1] = String.valueOf(timeout).getBytes();
return args; return args;
} }
@@ -207,9 +204,8 @@ abstract class SrpUtils {
} }
static Object[] limitParams(long offset, long count) { static Object[] limitParams(long offset, long count) {
return new Object[] { "LIMIT".getBytes(Charsets.UTF_8), return new Object[] { "LIMIT".getBytes(Charsets.UTF_8), String.valueOf(offset).getBytes(Charsets.UTF_8),
String.valueOf(offset).getBytes(Charsets.UTF_8), String.valueOf(count).getBytes(Charsets.UTF_8) };
String.valueOf(count).getBytes(Charsets.UTF_8)};
} }
static byte[] sort(SortParameters params) { static byte[] sort(SortParameters params) {
@@ -220,17 +216,17 @@ abstract class SrpUtils {
List<byte[]> arrays = new ArrayList<byte[]>(); List<byte[]> arrays = new ArrayList<byte[]>();
Object[] sortParams = sortParams(params, sortKey); Object[] sortParams = sortParams(params, sortKey);
for(Object param: sortParams) { for (Object param : sortParams) {
arrays.add((byte[])param); arrays.add((byte[]) param);
arrays.add(SPACE); arrays.add(SPACE);
} }
arrays.remove(arrays.size()-1); arrays.remove(arrays.size() - 1);
// concatenate array // concatenate array
int size = 0; int size = 0;
for (Object bs : arrays) { for (Object bs : arrays) {
size += ((byte[])bs).length; size += ((byte[]) bs).length;
} }
byte[] result = new byte[size]; byte[] result = new byte[size];
@@ -250,7 +246,7 @@ abstract class SrpUtils {
static Object[] sortParams(SortParameters params, byte[] sortKey) { static Object[] sortParams(SortParameters params, byte[] sortKey) {
List<byte[]> arrays = new ArrayList<byte[]>(); List<byte[]> arrays = new ArrayList<byte[]>();
if(params != null) { if (params != null) {
if (params.getByPattern() != null) { if (params.getByPattern() != null) {
arrays.add(BY); arrays.add(BY);
arrays.add(params.getByPattern()); arrays.add(params.getByPattern());
@@ -297,20 +293,20 @@ abstract class SrpUtils {
} }
static List<Boolean> asBooleanList(Reply reply) { static List<Boolean> asBooleanList(Reply reply) {
if(!(reply instanceof MultiBulkReply)) { if (!(reply instanceof MultiBulkReply)) {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
List<Boolean> results = new ArrayList<Boolean>(); List<Boolean> results = new ArrayList<Boolean>();
for(Reply r: ((MultiBulkReply)reply).data()) { for (Reply r : ((MultiBulkReply) reply).data()) {
results.add(SrpUtils.asBoolean((IntegerReply)r)); results.add(SrpUtils.asBoolean((IntegerReply) r));
} }
return results; return results;
} }
static List<Long> asIntegerList(Reply[] replies) { static List<Long> asIntegerList(Reply[] replies) {
List<Long> results = new ArrayList<Long>(); List<Long> results = new ArrayList<Long>();
for(Reply reply: replies) { for (Reply reply : replies) {
results.add(((IntegerReply)reply).data()); results.add(((IntegerReply) reply).data());
} }
return results; return results;
} }
@@ -318,23 +314,23 @@ abstract class SrpUtils {
static List<Object> asList(MultiBulkReply genericReply) { static List<Object> asList(MultiBulkReply genericReply) {
Reply[] replies = genericReply.data(); Reply[] replies = genericReply.data();
List<Object> results = new ArrayList<Object>(); List<Object> results = new ArrayList<Object>();
for(Reply reply: replies) { for (Reply reply : replies) {
results.add(reply.data()); results.add(reply.data());
} }
return results; return results;
} }
static Object convertScriptReturn(ReturnType returnType, Reply reply) { static Object convertScriptReturn(ReturnType returnType, Reply reply) {
if(reply instanceof MultiBulkReply) { if (reply instanceof MultiBulkReply) {
return SrpUtils.asList((MultiBulkReply)reply); return SrpUtils.asList((MultiBulkReply) reply);
} }
if(returnType == ReturnType.BOOLEAN) { if (returnType == ReturnType.BOOLEAN) {
// Lua false comes back as a null bulk reply // Lua false comes back as a null bulk reply
if(reply.data() == null) { if (reply.data() == null) {
return Boolean.FALSE; return Boolean.FALSE;
} }
return ((Long)reply.data() == 1); return ((Long) reply.data() == 1);
} }
return reply.data(); return reply.data();
} }
} }

View File

@@ -26,8 +26,8 @@ import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
/** /**
* Base implementation for a subscription handling the channel/pattern registration so subclasses only have to deal * Base implementation for a subscription handling the channel/pattern registration so subclasses only have to deal with
* with the actual registration/unregistration. * the actual registration/unregistration.
* *
* @author Costin Leau * @author Costin Leau
*/ */
@@ -43,10 +43,10 @@ public abstract class AbstractSubscription implements Subscription {
} }
/** /**
* Constructs a new <code>AbstractSubscription</code> instance. Allows channels and patterns to be added * Constructs a new <code>AbstractSubscription</code> instance. Allows channels and patterns to be added to the
* to the subscription w/o triggering a subscription action (as some clients (Jedis) require an initial call * subscription w/o triggering a subscription action (as some clients (Jedis) require an initial call before entering
* before entering into listening mode). * into listening mode).
* *
* @param listener * @param listener
* @param channels * @param channels
* @param patterns * @param patterns
@@ -98,26 +98,22 @@ public abstract class AbstractSubscription implements Subscription {
*/ */
protected abstract void doClose(); protected abstract void doClose();
public MessageListener getListener() { public MessageListener getListener() {
return listener; return listener;
} }
public Collection<byte[]> getChannels() { public Collection<byte[]> getChannels() {
synchronized (channels) { synchronized (channels) {
return clone(channels); return clone(channels);
} }
} }
public Collection<byte[]> getPatterns() { public Collection<byte[]> getPatterns() {
synchronized (patterns) { synchronized (patterns) {
return clone(patterns); return clone(patterns);
} }
} }
public void pSubscribe(byte[]... patterns) { public void pSubscribe(byte[]... patterns) {
checkPulse(); checkPulse();
@@ -130,13 +126,10 @@ public abstract class AbstractSubscription implements Subscription {
doPsubscribe(patterns); doPsubscribe(patterns);
} }
public void pUnsubscribe() { public void pUnsubscribe() {
pUnsubscribe((byte[][]) null); pUnsubscribe((byte[][]) null);
} }
public void subscribe(byte[]... channels) { public void subscribe(byte[]... channels) {
checkPulse(); checkPulse();
@@ -149,12 +142,10 @@ public abstract class AbstractSubscription implements Subscription {
doSubscribe(channels); doSubscribe(channels);
} }
public void unsubscribe() { public void unsubscribe() {
unsubscribe((byte[][]) null); unsubscribe((byte[][]) null);
} }
public void pUnsubscribe(byte[]... patts) { public void pUnsubscribe(byte[]... patts) {
if (!isAlive()) { if (!isAlive()) {
return; return;
@@ -168,13 +159,11 @@ public abstract class AbstractSubscription implements Subscription {
doPUnsubscribe(true, patts); doPUnsubscribe(true, patts);
this.patterns.clear(); this.patterns.clear();
} }
} } else {
else {
// nothing to unsubscribe from // nothing to unsubscribe from
return; return;
} }
} } else {
else {
doPUnsubscribe(false, patts); doPUnsubscribe(false, patts);
synchronized (this.patterns) { synchronized (this.patterns) {
remove(this.patterns, patts); remove(this.patterns, patts);
@@ -184,7 +173,6 @@ public abstract class AbstractSubscription implements Subscription {
closeIfUnsubscribed(); closeIfUnsubscribed();
} }
public void unsubscribe(byte[]... chans) { public void unsubscribe(byte[]... chans) {
if (!isAlive()) { if (!isAlive()) {
return; return;
@@ -198,13 +186,11 @@ public abstract class AbstractSubscription implements Subscription {
doUnsubscribe(true, chans); doUnsubscribe(true, chans);
this.channels.clear(); this.channels.clear();
} }
} } else {
else {
// nothing to unsubscribe from // nothing to unsubscribe from
return; return;
} }
} } else {
else {
doUnsubscribe(false, chans); doUnsubscribe(false, chans);
synchronized (this.channels) { synchronized (this.channels) {
remove(this.channels, chans); remove(this.channels, chans);
@@ -214,7 +200,6 @@ public abstract class AbstractSubscription implements Subscription {
closeIfUnsubscribed(); closeIfUnsubscribed();
} }
public boolean isAlive() { public boolean isAlive() {
return alive.get(); return alive.get();
} }
@@ -232,7 +217,6 @@ public abstract class AbstractSubscription implements Subscription {
} }
} }
private static Collection<byte[]> clone(Collection<ByteArrayWrapper> col) { private static Collection<byte[]> clone(Collection<ByteArrayWrapper> col) {
Collection<byte[]> list = new ArrayList<byte[]>(col.size()); Collection<byte[]> list = new ArrayList<byte[]>(col.size());
for (ByteArrayWrapper wrapper : col) { for (ByteArrayWrapper wrapper : col) {
@@ -241,7 +225,6 @@ public abstract class AbstractSubscription implements Subscription {
return list; return list;
} }
private static void add(Collection<ByteArrayWrapper> col, byte[]... bytes) { private static void add(Collection<ByteArrayWrapper> col, byte[]... bytes) {
if (!ObjectUtils.isEmpty(bytes)) { if (!ObjectUtils.isEmpty(bytes)) {
for (byte[] bs : bytes) { for (byte[] bs : bytes) {
@@ -257,4 +240,4 @@ public abstract class AbstractSubscription implements Subscription {
} }
} }
} }
} }

View File

@@ -2,73 +2,55 @@ package org.springframework.data.redis.connection.util;
import java.util.Arrays; import java.util.Arrays;
/** /**
* A very fast and memory efficient class to encode and decode to and from BASE64 in full accordance * A very fast and memory efficient class to encode and decode to and from BASE64 in full accordance with RFC 2045.<br>
* with RFC 2045.<br><br> * <br>
* On Windows XP sp1 with 1.4.2_04 and later ;), this encoder and decoder is about 10 times faster * On Windows XP sp1 with 1.4.2_04 and later ;), this encoder and decoder is about 10 times faster on small arrays (10 -
* on small arrays (10 - 1000 bytes) and 2-3 times as fast on larger arrays (10000 - 1000000 bytes) * 1000 bytes) and 2-3 times as fast on larger arrays (10000 - 1000000 bytes) compared to
* compared to <code>sun.misc.Encoder()/Decoder()</code>.<br><br> * <code>sun.misc.Encoder()/Decoder()</code>.<br>
* * <br>
* On byte arrays the encoder is about 20% faster than Jakarta Commons Base64 Codec for encode and * On byte arrays the encoder is about 20% faster than Jakarta Commons Base64 Codec for encode and about 50% faster for
* about 50% faster for decoding large arrays. This implementation is about twice as fast on very small * decoding large arrays. This implementation is about twice as fast on very small arrays (&lt 30 bytes). If
* arrays (&lt 30 bytes). If source/destination is a <code>String</code> this * source/destination is a <code>String</code> this version is about three times as fast due to the fact that the
* version is about three times as fast due to the fact that the Commons Codec result has to be recoded * Commons Codec result has to be recoded to a <code>String</code> from <code>byte[]</code>, which is very expensive.<br>
* to a <code>String</code> from <code>byte[]</code>, which is very expensive.<br><br> * <br>
* * This encode/decode algorithm doesn't create any temporary arrays as many other codecs do, it only allocates the
* This encode/decode algorithm doesn't create any temporary arrays as many other codecs do, it only * resulting array. This produces less garbage and it is possible to handle arrays twice as large as algorithms that
* allocates the resulting array. This produces less garbage and it is possible to handle arrays twice * create a temporary array. (E.g. Jakarta Commons Codec). It is unknown whether Sun's
* as large as algorithms that create a temporary array. (E.g. Jakarta Commons Codec). It is unknown * <code>sun.misc.Encoder()/Decoder()</code> produce temporary arrays but since performance is quite low it probably
* whether Sun's <code>sun.misc.Encoder()/Decoder()</code> produce temporary arrays but since performance * does.<br>
* is quite low it probably does.<br><br> * <br>
* * The encoder produces the same output as the Sun one except that the Sun's encoder appends a trailing line separator
* The encoder produces the same output as the Sun one except that the Sun's encoder appends * if the last character isn't a pad. Unclear why but it only adds to the length and is probably a side effect. Both are
* a trailing line separator if the last character isn't a pad. Unclear why but it only adds to the * in conformance with RFC 2045 though.<br>
* length and is probably a side effect. Both are in conformance with RFC 2045 though.<br> * Commons codec seem to always att a trailing line separator.<br>
* Commons codec seem to always att a trailing line separator.<br><br> * <br>
* * <b>Note!</b> The encode/decode method pairs (types) come in three versions with the <b>exact</b> same algorithm and
* <b>Note!</b> * thus a lot of code redundancy. This is to not create any temporary arrays for transcoding to/from different format
* The encode/decode method pairs (types) come in three versions with the <b>exact</b> same algorithm and * types. The methods not used can simply be commented out.<br>
* thus a lot of code redundancy. This is to not create any temporary arrays for transcoding to/from different * <br>
* format types. The methods not used can simply be commented out.<br><br> * There is also a "fast" version of all decode methods that works the same way as the normal ones, but har a few
* * demands on the decoded input. Normally though, these fast verions should be used if the source if the input is known
* There is also a "fast" version of all decode methods that works the same way as the normal ones, but * and it hasn't bee tampered with.<br>
* har a few demands on the decoded input. Normally though, these fast verions should be used if the source if * <br>
* the input is known and it hasn't bee tampered with.<br><br> * If you find the code useful or you find a bug, please send me a note at base64 @ miginfocom . com. Licence (BSD):
* * ============== Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (base64 @ miginfocom . com) All rights reserved.
* If you find the code useful or you find a bug, please send me a note at base64 @ miginfocom . com. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* * following conditions are met: Redistributions of source code must retain the above copyright notice, this list of
* Licence (BSD): * conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice,
* ============== * this list of conditions and the following disclaimer in the documentation and/or other materials provided with the
* * distribution. Neither the name of the MiG InfoCom AB nor the names of its contributors may be used to endorse or
* Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (base64 @ miginfocom . com) * promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY
* All rights reserved. * THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* Redistribution and use in source and binary forms, with or without modification, * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* are permitted provided that the following conditions are met: * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* Redistributions of source code must retain the above copyright notice, this list * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* of conditions and the following disclaimer. * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* Redistributions in binary form must reproduce the above copyright notice, this * POSSIBILITY OF SUCH DAMAGE.
* list of conditions and the following disclaimer in the documentation and/or other *
* materials provided with the distribution.
* Neither the name of the MiG InfoCom AB nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* @version 2.2 * @version 2.2
* @author Mikael Grev * @author Mikael Grev Date: 2004-aug-02 Time: 11:31:11
* Date: 2004-aug-02
* Time: 11:31:11
*/ */
class Base64 { class Base64 {
@@ -82,14 +64,16 @@ class Base64 {
} }
// **************************************************************************************** // ****************************************************************************************
// * char[] version // * char[] version
// **************************************************************************************** // ****************************************************************************************
/** Encodes a raw byte array into a BASE64 <code>char[]</code> representation i accordance with RFC 2045. /**
* Encodes a raw byte array into a BASE64 <code>char[]</code> representation i accordance with RFC 2045.
*
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned. * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br> * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a little
* little faster. * faster.
* @return A BASE64 encoded array. Never <code>null</code>. * @return A BASE64 encoded array. Never <code>null</code>.
*/ */
public final static char[] encodeToChar(byte[] sArr, boolean lineSep) { public final static char[] encodeToChar(byte[] sArr, boolean lineSep) {
@@ -137,11 +121,13 @@ class Base64 {
return dArr; return dArr;
} }
/** Decodes a BASE64 encoded char array. All illegal characters will be ignored and can handle both arrays with /**
* and without line separators. * Decodes a BASE64 encoded char array. All illegal characters will be ignored and can handle both arrays with and
* without line separators.
*
* @param sArr The source array. <code>null</code> or length 0 will return an empty array. * @param sArr The source array. <code>null</code> or length 0 will return an empty array.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted). * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/ */
public final static byte[] decode(char[] sArr) { public final static byte[] decode(char[] sArr) {
// Check special case // Check special case
@@ -191,12 +177,14 @@ class Base64 {
return dArr; return dArr;
} }
/** Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as /**
* fast as {@link #decode(char[])}. The preconditions are:<br> * Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as fast
* as {@link #decode(char[])}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br> * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045 * + Line separator must be "\r\n", as specified in RFC 2045 + The array must not contain illegal characters within
* + The array must not contain illegal characters within the encoded string<br> * the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br> * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
*
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception. * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0. * @return The decoded array of bytes. May be of length 0.
*/ */
@@ -256,14 +244,16 @@ class Base64 {
} }
// **************************************************************************************** // ****************************************************************************************
// * byte[] version // * byte[] version
// **************************************************************************************** // ****************************************************************************************
/** Encodes a raw byte array into a BASE64 <code>byte[]</code> representation i accordance with RFC 2045. /**
* Encodes a raw byte array into a BASE64 <code>byte[]</code> representation i accordance with RFC 2045.
*
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned. * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br> * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a little
* little faster. * faster.
* @return A BASE64 encoded array. Never <code>null</code>. * @return A BASE64 encoded array. Never <code>null</code>.
*/ */
public final static byte[] encodeToByte(byte[] sArr, boolean lineSep) { public final static byte[] encodeToByte(byte[] sArr, boolean lineSep) {
@@ -311,11 +301,13 @@ class Base64 {
return dArr; return dArr;
} }
/** Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle both arrays with /**
* and without line separators. * Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle both arrays with and
* without line separators.
*
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception. * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted). * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/ */
public final static byte[] decode(byte[] sArr) { public final static byte[] decode(byte[] sArr) {
// Check special case // Check special case
@@ -365,13 +357,14 @@ class Base64 {
return dArr; return dArr;
} }
/**
/** Decodes a BASE64 encoded byte array that is known to be resonably well formatted. The method is about twice as * Decodes a BASE64 encoded byte array that is known to be resonably well formatted. The method is about twice as fast
* fast as {@link #decode(byte[])}. The preconditions are:<br> * as {@link #decode(byte[])}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br> * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045 * + Line separator must be "\r\n", as specified in RFC 2045 + The array must not contain illegal characters within
* + The array must not contain illegal characters within the encoded string<br> * the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br> * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
*
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception. * @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0. * @return The decoded array of bytes. May be of length 0.
*/ */
@@ -434,11 +427,13 @@ class Base64 {
// * String version // * String version
// **************************************************************************************** // ****************************************************************************************
/** Encodes a raw byte array into a BASE64 <code>String</code> representation i accordance with RFC 2045. /**
* Encodes a raw byte array into a BASE64 <code>String</code> representation i accordance with RFC 2045.
*
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned. * @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br> * @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a * No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a little
* little faster. * faster.
* @return A BASE64 encoded array. Never <code>null</code>. * @return A BASE64 encoded array. Never <code>null</code>.
*/ */
public final static String encodeToString(byte[] sArr, boolean lineSep) { public final static String encodeToString(byte[] sArr, boolean lineSep) {
@@ -446,13 +441,15 @@ class Base64 {
return new String(encodeToChar(sArr, lineSep)); return new String(encodeToChar(sArr, lineSep));
} }
/** Decodes a BASE64 encoded <code>String</code>. All illegal characters will be ignored and can handle both strings with /**
* and without line separators.<br> * Decodes a BASE64 encoded <code>String</code>. All illegal characters will be ignored and can handle both strings
* <b>Note!</b> It can be up to about 2x the speed to call <code>decode(str.toCharArray())</code> instead. That * with and without line separators.<br>
* will create a temporary array though. This version will use <code>str.charAt(i)</code> to iterate the string. * <b>Note!</b> It can be up to about 2x the speed to call <code>decode(str.toCharArray())</code> instead. That will
* create a temporary array though. This version will use <code>str.charAt(i)</code> to iterate the string.
*
* @param str The source string. <code>null</code> or length 0 will return an empty array. * @param str The source string. <code>null</code> or length 0 will return an empty array.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters * @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted). * (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/ */
public final static byte[] decode(String str) { public final static byte[] decode(String str) {
// Check special case // Check special case
@@ -503,12 +500,14 @@ class Base64 {
return dArr; return dArr;
} }
/** Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as /**
* fast as {@link #decode(String)}. The preconditions are:<br> * Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as fast as
* {@link #decode(String)}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br> * + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045 * + Line separator must be "\r\n", as specified in RFC 2045 + The array must not contain illegal characters within
* + The array must not contain illegal characters within the encoded string<br> * the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br> * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
*
* @param s The source string. Length 0 will return an empty array. <code>null</code> will throw an exception. * @param s The source string. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0. * @return The decoded array of bytes. May be of length 0.
*/ */
@@ -540,8 +539,7 @@ class Base64 {
int d = 0; int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
// Assemble three bytes into an int from four "valid" characters. // Assemble three bytes into an int from four "valid" characters.
int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6 int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6 | IA[s.charAt(sIx++)];
| IA[s.charAt(sIx++)];
// Add the bytes // Add the bytes
dArr[d++] = (byte) (i >> 16); dArr[d++] = (byte) (i >> 16);
@@ -567,4 +565,4 @@ class Base64 {
return dArr; return dArr;
} }
} }

View File

@@ -19,7 +19,7 @@ import java.util.Arrays;
/** /**
* Simple wrapper class used for wrapping arrays so they can be used as keys inside maps. * Simple wrapper class used for wrapping arrays so they can be used as keys inside maps.
* *
* @author Costin Leau * @author Costin Leau
*/ */
public class ByteArrayWrapper { public class ByteArrayWrapper {
@@ -32,7 +32,6 @@ public class ByteArrayWrapper {
this.hashCode = Arrays.hashCode(array); this.hashCode = Arrays.hashCode(array);
} }
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof ByteArrayWrapper) { if (obj instanceof ByteArrayWrapper) {
return Arrays.equals(array, ((ByteArrayWrapper) obj).array); return Arrays.equals(array, ((ByteArrayWrapper) obj).array);
@@ -41,14 +40,13 @@ public class ByteArrayWrapper {
return false; return false;
} }
public int hashCode() { public int hashCode() {
return hashCode; return hashCode;
} }
/** /**
* Returns the array. * Returns the array.
* *
* @return Returns the array * @return Returns the array
*/ */
public byte[] getArray() { public byte[] getArray() {

View File

@@ -79,4 +79,4 @@ public abstract class DecodeUtils {
} }
return set; return set;
} }
} }

View File

@@ -46,7 +46,6 @@ abstract class AbstractOperations<K, V> {
this.key = key; this.key = key;
} }
public final V doInRedis(RedisConnection connection) { public final V doInRedis(RedisConnection connection) {
byte[] result = inRedis(rawKey(key), connection); byte[] result = inRedis(rawKey(key), connection);
return deserializeValue(result); return deserializeValue(result);
@@ -81,7 +80,6 @@ abstract class AbstractOperations<K, V> {
return template.getStringSerializer(); return template.getStringSerializer();
} }
<T> T execute(RedisCallback<T> callback, boolean b) { <T> T execute(RedisCallback<T> callback, boolean b) {
return template.execute(callback, b); return template.execute(callback, b);
} }
@@ -93,8 +91,8 @@ abstract class AbstractOperations<K, V> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
byte[] rawKey(Object key) { byte[] rawKey(Object key) {
Assert.notNull(key, "non null key required"); Assert.notNull(key, "non null key required");
if(keySerializer() == null && key instanceof byte[]) { if (keySerializer() == null && key instanceof byte[]) {
return (byte[])key; return (byte[]) key;
} }
return keySerializer().serialize(key); return keySerializer().serialize(key);
} }
@@ -106,8 +104,8 @@ abstract class AbstractOperations<K, V> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
byte[] rawValue(Object value) { byte[] rawValue(Object value) {
if(valueSerializer() == null && value instanceof byte[]) { if (valueSerializer() == null && value instanceof byte[]) {
return (byte[])value; return (byte[]) value;
} }
return valueSerializer().serialize(value); return valueSerializer().serialize(value);
} }
@@ -124,8 +122,8 @@ abstract class AbstractOperations<K, V> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
<HK> byte[] rawHashKey(HK hashKey) { <HK> byte[] rawHashKey(HK hashKey) {
Assert.notNull(hashKey, "non null hash key required"); Assert.notNull(hashKey, "non null hash key required");
if(hashKeySerializer() == null && hashKey instanceof byte[]) { if (hashKeySerializer() == null && hashKey instanceof byte[]) {
return (byte[])hashKey; return (byte[]) hashKey;
} }
return hashKeySerializer().serialize(hashKey); return hashKeySerializer().serialize(hashKey);
} }
@@ -141,8 +139,8 @@ abstract class AbstractOperations<K, V> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
<HV> byte[] rawHashValue(HV value) { <HV> byte[] rawHashValue(HV value) {
if(hashValueSerializer() == null & value instanceof byte[]) { if (hashValueSerializer() == null & value instanceof byte[]) {
return (byte[])value; return (byte[]) value;
} }
return hashValueSerializer().serialize(value); return hashValueSerializer().serialize(value);
} }
@@ -150,7 +148,6 @@ abstract class AbstractOperations<K, V> {
byte[][] rawKeys(K key, K otherKey) { byte[][] rawKeys(K key, K otherKey) {
final byte[][] rawKeys = new byte[2][]; final byte[][] rawKeys = new byte[2][];
rawKeys[0] = rawKey(key); rawKeys[0] = rawKey(key);
rawKeys[1] = rawKey(key); rawKeys[1] = rawKey(key);
return rawKeys; return rawKeys;
@@ -178,21 +175,21 @@ abstract class AbstractOperations<K, V> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Set<V> deserializeValues(Set<byte[]> rawValues) { Set<V> deserializeValues(Set<byte[]> rawValues) {
if(valueSerializer() == null) { if (valueSerializer() == null) {
return (Set<V>)rawValues; return (Set<V>) rawValues;
} }
return SerializationUtils.deserialize(rawValues, valueSerializer()); return SerializationUtils.deserialize(rawValues, valueSerializer());
} }
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
Set<TypedTuple<V>> deserializeTupleValues(Set<Tuple> rawValues) { Set<TypedTuple<V>> deserializeTupleValues(Set<Tuple> rawValues) {
if(rawValues == null) { if (rawValues == null) {
return null; return null;
} }
Set<TypedTuple<V>> set = new LinkedHashSet<TypedTuple<V>>(rawValues.size()); Set<TypedTuple<V>> set = new LinkedHashSet<TypedTuple<V>>(rawValues.size());
for (Tuple rawValue : rawValues) { for (Tuple rawValue : rawValues) {
Object value = rawValue.getValue(); Object value = rawValue.getValue();
if(valueSerializer() != null) { if (valueSerializer() != null) {
value = valueSerializer().deserialize(rawValue.getValue()); value = valueSerializer().deserialize(rawValue.getValue());
} }
set.add(new DefaultTypedTuple(value, rawValue.getScore())); set.add(new DefaultTypedTuple(value, rawValue.getScore()));
@@ -202,15 +199,15 @@ abstract class AbstractOperations<K, V> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Set<Tuple> rawTupleValues(Set<TypedTuple<V>> values) { Set<Tuple> rawTupleValues(Set<TypedTuple<V>> values) {
if(values == null) { if (values == null) {
return null; return null;
} }
Set<Tuple> rawTuples = new LinkedHashSet<Tuple>(values.size()); Set<Tuple> rawTuples = new LinkedHashSet<Tuple>(values.size());
for(TypedTuple<V> value: values) { for (TypedTuple<V> value : values) {
byte[] rawValue; byte[] rawValue;
if(valueSerializer() == null && value.getValue() instanceof byte[]) { if (valueSerializer() == null && value.getValue() instanceof byte[]) {
rawValue = (byte[]) value.getValue(); rawValue = (byte[]) value.getValue();
}else { } else {
rawValue = valueSerializer().serialize(value.getValue()); rawValue = valueSerializer().serialize(value.getValue());
} }
rawTuples.add(new DefaultTuple(rawValue, value.getScore())); rawTuples.add(new DefaultTuple(rawValue, value.getScore()));
@@ -220,24 +217,24 @@ abstract class AbstractOperations<K, V> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<V> deserializeValues(List<byte[]> rawValues) { List<V> deserializeValues(List<byte[]> rawValues) {
if(valueSerializer() == null) { if (valueSerializer() == null) {
return (List<V>)rawValues; return (List<V>) rawValues;
} }
return SerializationUtils.deserialize(rawValues, valueSerializer()); return SerializationUtils.deserialize(rawValues, valueSerializer());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
<T> Set<T> deserializeHashKeys(Set<byte[]> rawKeys) { <T> Set<T> deserializeHashKeys(Set<byte[]> rawKeys) {
if(hashKeySerializer() == null) { if (hashKeySerializer() == null) {
return (Set<T>)rawKeys; return (Set<T>) rawKeys;
} }
return SerializationUtils.deserialize(rawKeys, hashKeySerializer()); return SerializationUtils.deserialize(rawKeys, hashKeySerializer());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
<T> List<T> deserializeHashValues(List<byte[]> rawValues) { <T> List<T> deserializeHashValues(List<byte[]> rawValues) {
if(hashValueSerializer() == null) { if (hashValueSerializer() == null) {
return (List<T>)rawValues; return (List<T>) rawValues;
} }
return SerializationUtils.deserialize(rawValues, hashValueSerializer()); return SerializationUtils.deserialize(rawValues, hashValueSerializer());
} }
@@ -260,7 +257,7 @@ abstract class AbstractOperations<K, V> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
K deserializeKey(byte[] value) { K deserializeKey(byte[] value) {
if(keySerializer() == null) { if (keySerializer() == null) {
return (K) value; return (K) value;
} }
return (K) keySerializer().deserialize(value); return (K) keySerializer().deserialize(value);
@@ -268,8 +265,8 @@ abstract class AbstractOperations<K, V> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
V deserializeValue(byte[] value) { V deserializeValue(byte[] value) {
if(valueSerializer() == null) { if (valueSerializer() == null) {
return (V)value; return (V) value;
} }
return (V) valueSerializer().deserialize(value); return (V) valueSerializer().deserialize(value);
} }
@@ -278,19 +275,19 @@ abstract class AbstractOperations<K, V> {
return (String) stringSerializer().deserialize(value); return (String) stringSerializer().deserialize(value);
} }
@SuppressWarnings( { "unchecked" }) @SuppressWarnings({ "unchecked" })
<HK> HK deserializeHashKey(byte[] value) { <HK> HK deserializeHashKey(byte[] value) {
if(hashKeySerializer() == null) { if (hashKeySerializer() == null) {
return (HK)value; return (HK) value;
} }
return (HK) hashKeySerializer().deserialize(value); return (HK) hashKeySerializer().deserialize(value);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
<HV> HV deserializeHashValue(byte[] value) { <HV> HV deserializeHashValue(byte[] value) {
if(hashValueSerializer() == null) { if (hashValueSerializer() == null) {
return (HV)value; return (HV) value;
} }
return (HV) hashValueSerializer().deserialize(value); return (HV) hashValueSerializer().deserialize(value);
} }
} }

View File

@@ -21,13 +21,12 @@ import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.connection.DataType; import org.springframework.data.redis.connection.DataType;
/** /**
* Operations over a Redis key. * Operations over a Redis key. Useful for executing common key-'bound' operations to all implementations.
* * <p>
* Useful for executing common key-'bound' operations to all implementations. * As the rest of the APIs, if the underlying connection is pipelined or queued/in multi mode, all methods will return
* * null.
* <p>As the rest of the APIs, if the underlying connection is pipelined or queued/in multi mode,
* all methods will return null.
* </p> * </p>
*
* @author Costin Leau * @author Costin Leau
*/ */
public interface BoundKeyOperations<K> { public interface BoundKeyOperations<K> {
@@ -41,13 +40,13 @@ public interface BoundKeyOperations<K> {
/** /**
* Returns the associated Redis type. * Returns the associated Redis type.
* *
* @return key type * @return key type
*/ */
DataType getType(); DataType getType();
/** /**
* Returns the expiration of this key. * Returns the expiration of this key.
* *
* @return expiration value (in seconds) * @return expiration value (in seconds)
*/ */
@@ -72,6 +71,7 @@ public interface BoundKeyOperations<K> {
/** /**
* Removes the expiration (if any) of the key. * Removes the expiration (if any) of the key.
*
* @return true if expiration was removed, false otherwise * @return true if expiration was removed, false otherwise
*/ */
Boolean persist(); Boolean persist();
@@ -82,4 +82,4 @@ public interface BoundKeyOperations<K> {
* @param newKey new key * @param newKey new key
*/ */
void rename(K newKey); void rename(K newKey);
} }

View File

@@ -18,7 +18,7 @@ package org.springframework.data.redis.core;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
* Value (or String in Redis terminology) operations bound to a certain key. * Value (or String in Redis terminology) operations bound to a certain key.
* *
* @author Costin Leau * @author Costin Leau
*/ */

View File

@@ -21,7 +21,6 @@ import java.util.Set;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple; import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
/** /**
* ZSet (or SortedSet) operations bound to a certain key. * ZSet (or SortedSet) operations bound to a certain key.
* *

View File

@@ -18,8 +18,8 @@ package org.springframework.data.redis.core;
import java.util.List; import java.util.List;
/** /**
* Mapper translating Redis bulk value responses (typically returned by a sort query) to actual objects. Implementations of this interface do not have to worry * Mapper translating Redis bulk value responses (typically returned by a sort query) to actual objects. Implementations
* about exception or connection handling. * of this interface do not have to worry about exception or connection handling.
* <p/> * <p/>
* Typically used by {@link RedisTemplate} <tt>sort</tt> methods. * Typically used by {@link RedisTemplate} <tt>sort</tt> methods.
* *

View File

@@ -22,10 +22,11 @@ import java.lang.reflect.Method;
import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnection;
/** /**
* Invocation handler that suppresses close calls on {@link RedisConnection}. * Invocation handler that suppresses close calls on {@link RedisConnection}.
* @see RedisConnection#close() *
* @author Costin Leau * @see RedisConnection#close()
*/ * @author Costin Leau
*/
class CloseSuppressingInvocationHandler implements InvocationHandler { class CloseSuppressingInvocationHandler implements InvocationHandler {
private static final String CLOSE = "close"; private static final String CLOSE = "close";
@@ -43,12 +44,10 @@ class CloseSuppressingInvocationHandler implements InvocationHandler {
if (method.getName().equals(EQUALS)) { if (method.getName().equals(EQUALS)) {
// Only consider equal when proxies are identical. // Only consider equal when proxies are identical.
return (proxy == args[0]); return (proxy == args[0]);
} } else if (method.getName().equals(HASH_CODE)) {
else if (method.getName().equals(HASH_CODE)) {
// Use hashCode of PersistenceManager proxy. // Use hashCode of PersistenceManager proxy.
return System.identityHashCode(proxy); return System.identityHashCode(proxy);
} } else if (method.getName().equals(CLOSE)) {
else if (method.getName().equals(CLOSE)) {
// Handle close method: suppress, not valid. // Handle close method: suppress, not valid.
return null; return null;
} }
@@ -61,4 +60,4 @@ class CloseSuppressingInvocationHandler implements InvocationHandler {
throw ex.getTargetException(); throw ex.getTargetException();
} }
} }
} }

View File

@@ -27,13 +27,14 @@ import org.springframework.data.redis.connection.DataType;
* *
* @author Costin Leau * @author Costin Leau
*/ */
class DefaultBoundHashOperations<H, HK, HV> extends DefaultBoundKeyOperations<H> implements BoundHashOperations<H, HK, HV> { class DefaultBoundHashOperations<H, HK, HV> extends DefaultBoundKeyOperations<H> implements
BoundHashOperations<H, HK, HV> {
private final HashOperations<H, HK, HV> ops; private final HashOperations<H, HK, HV> ops;
/** /**
* Constructs a new <code>DefaultBoundHashOperations</code> instance. * Constructs a new <code>DefaultBoundHashOperations</code> instance.
* *
* @param key * @param key
* @param template * @param template
*/ */
@@ -42,32 +43,26 @@ class DefaultBoundHashOperations<H, HK, HV> extends DefaultBoundKeyOperations<H>
this.ops = operations.opsForHash(); this.ops = operations.opsForHash();
} }
public void delete(Object... keys) { public void delete(Object... keys) {
ops.delete(getKey(), keys); ops.delete(getKey(), keys);
} }
public HV get(Object key) { public HV get(Object key) {
return ops.get(getKey(), key); return ops.get(getKey(), key);
} }
public List<HV> multiGet(Collection<HK> hashKeys) { public List<HV> multiGet(Collection<HK> hashKeys) {
return ops.multiGet(getKey(), hashKeys); return ops.multiGet(getKey(), hashKeys);
} }
public RedisOperations<H, ?> getOperations() { public RedisOperations<H, ?> getOperations() {
return ops.getOperations(); return ops.getOperations();
} }
public Boolean hasKey(Object key) { public Boolean hasKey(Object key) {
return ops.hasKey(getKey(), key); return ops.hasKey(getKey(), key);
} }
public Long increment(HK key, long delta) { public Long increment(HK key, long delta) {
return ops.increment(getKey(), key, delta); return ops.increment(getKey(), key, delta);
} }
@@ -80,38 +75,31 @@ class DefaultBoundHashOperations<H, HK, HV> extends DefaultBoundKeyOperations<H>
return ops.keys(getKey()); return ops.keys(getKey());
} }
public Long size() { public Long size() {
return ops.size(getKey()); return ops.size(getKey());
} }
public void putAll(Map<? extends HK, ? extends HV> m) { public void putAll(Map<? extends HK, ? extends HV> m) {
ops.putAll(getKey(), m); ops.putAll(getKey(), m);
} }
public void put(HK key, HV value) { public void put(HK key, HV value) {
ops.put(getKey(), key, value); ops.put(getKey(), key, value);
} }
public Boolean putIfAbsent(HK key, HV value) { public Boolean putIfAbsent(HK key, HV value) {
return ops.putIfAbsent(getKey(), key, value); return ops.putIfAbsent(getKey(), key, value);
} }
public List<HV> values() { public List<HV> values() {
return ops.values(getKey()); return ops.values(getKey());
} }
public Map<HK, HV> entries() { public Map<HK, HV> entries() {
return ops.entries(getKey()); return ops.entries(getKey());
} }
public DataType getType() { public DataType getType() {
return DataType.HASH; return DataType.HASH;
} }
} }

View File

@@ -18,10 +18,8 @@ package org.springframework.data.redis.core;
import java.util.Date; import java.util.Date;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
* Default {@link BoundKeyOperations} implementation. * Default {@link BoundKeyOperations} implementation. Meant for internal usage.
* Meant for internal usage.
* *
* @author Costin Leau * @author Costin Leau
*/ */
@@ -35,7 +33,6 @@ abstract class DefaultBoundKeyOperations<K> implements BoundKeyOperations<K> {
this.ops = operations; this.ops = operations;
} }
public K getKey() { public K getKey() {
return key; return key;
} }
@@ -44,31 +41,26 @@ abstract class DefaultBoundKeyOperations<K> implements BoundKeyOperations<K> {
this.key = key; this.key = key;
} }
public Boolean expire(long timeout, TimeUnit unit) { public Boolean expire(long timeout, TimeUnit unit) {
return ops.expire(key, timeout, unit); return ops.expire(key, timeout, unit);
} }
public Boolean expireAt(Date date) { public Boolean expireAt(Date date) {
return ops.expireAt(key, date); return ops.expireAt(key, date);
} }
public Long getExpire() { public Long getExpire() {
return ops.getExpire(key); return ops.getExpire(key);
} }
public Boolean persist() { public Boolean persist() {
return ops.persist(key); return ops.persist(key);
} }
public void rename(K newKey) { public void rename(K newKey) {
if (ops.hasKey(key)) { if (ops.hasKey(key)) {
ops.rename(key, newKey); ops.rename(key, newKey);
} }
key = newKey; key = newKey;
} }
} }

View File

@@ -20,7 +20,6 @@ import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.connection.DataType; import org.springframework.data.redis.connection.DataType;
/** /**
* Default implementation for {@link BoundListOperations}. * Default implementation for {@link BoundListOperations}.
* *
@@ -32,7 +31,7 @@ class DefaultBoundListOperations<K, V> extends DefaultBoundKeyOperations<K> impl
/** /**
* Constructs a new <code>DefaultBoundListOperations</code> instance. * Constructs a new <code>DefaultBoundListOperations</code> instance.
* *
* @param key * @param key
* @param operations * @param operations
*/ */
@@ -41,28 +40,22 @@ class DefaultBoundListOperations<K, V> extends DefaultBoundKeyOperations<K> impl
this.ops = operations.opsForList(); this.ops = operations.opsForList();
} }
public RedisOperations<K, V> getOperations() { public RedisOperations<K, V> getOperations() {
return ops.getOperations(); return ops.getOperations();
} }
public V index(long index) { public V index(long index) {
return ops.index(getKey(), index); return ops.index(getKey(), index);
} }
public V leftPop() { public V leftPop() {
return ops.leftPop(getKey()); return ops.leftPop(getKey());
} }
public V leftPop(long timeout, TimeUnit unit) { public V leftPop(long timeout, TimeUnit unit) {
return ops.leftPop(getKey(), timeout, unit); return ops.leftPop(getKey(), timeout, unit);
} }
public Long leftPush(V value) { public Long leftPush(V value) {
return ops.leftPush(getKey(), value); return ops.leftPush(getKey(), value);
} }
@@ -70,47 +63,39 @@ class DefaultBoundListOperations<K, V> extends DefaultBoundKeyOperations<K> impl
public Long leftPushAll(V... values) { public Long leftPushAll(V... values) {
return ops.leftPushAll(getKey(), values); return ops.leftPushAll(getKey(), values);
} }
public Long leftPushIfPresent(V value) { public Long leftPushIfPresent(V value) {
return ops.leftPushIfPresent(getKey(), value); return ops.leftPushIfPresent(getKey(), value);
} }
public Long leftPush(V pivot, V value) { public Long leftPush(V pivot, V value) {
return ops.leftPush(getKey(), pivot, value); return ops.leftPush(getKey(), pivot, value);
} }
public Long size() { public Long size() {
return ops.size(getKey()); return ops.size(getKey());
} }
public List<V> range(long start, long end) { public List<V> range(long start, long end) {
return ops.range(getKey(), start, end); return ops.range(getKey(), start, end);
} }
public Long remove(long i, Object value) { public Long remove(long i, Object value) {
return ops.remove(getKey(), i, value); return ops.remove(getKey(), i, value);
} }
public V rightPop() { public V rightPop() {
return ops.rightPop(getKey()); return ops.rightPop(getKey());
} }
public V rightPop(long timeout, TimeUnit unit) { public V rightPop(long timeout, TimeUnit unit) {
return ops.rightPop(getKey(), timeout, unit); return ops.rightPop(getKey(), timeout, unit);
} }
public Long rightPushIfPresent(V value) { public Long rightPushIfPresent(V value) {
return ops.rightPushIfPresent(getKey(), value); return ops.rightPushIfPresent(getKey(), value);
} }
public Long rightPush(V value) { public Long rightPush(V value) {
return ops.rightPush(getKey(), value); return ops.rightPush(getKey(), value);
} }
@@ -123,18 +108,15 @@ class DefaultBoundListOperations<K, V> extends DefaultBoundKeyOperations<K> impl
return ops.rightPush(getKey(), pivot, value); return ops.rightPush(getKey(), pivot, value);
} }
public void trim(long start, long end) { public void trim(long start, long end) {
ops.trim(getKey(), start, end); ops.trim(getKey(), start, end);
} }
public void set(long index, V value) { public void set(long index, V value) {
ops.set(getKey(), index, value); ops.set(getKey(), index, value);
} }
public DataType getType() { public DataType getType() {
return DataType.LIST; return DataType.LIST;
} }
} }

View File

@@ -31,10 +31,9 @@ class DefaultBoundSetOperations<K, V> extends DefaultBoundKeyOperations<K> imple
private final SetOperations<K, V> ops; private final SetOperations<K, V> ops;
/** /**
* Constructs a new <code>DefaultBoundSetOperations</code> instance. * Constructs a new <code>DefaultBoundSetOperations</code> instance.
* *
* @param key * @param key
* @param operations * @param operations
*/ */
@@ -43,125 +42,99 @@ class DefaultBoundSetOperations<K, V> extends DefaultBoundKeyOperations<K> imple
this.ops = operations.opsForSet(); this.ops = operations.opsForSet();
} }
public Long add(V... values) { public Long add(V... values) {
return ops.add(getKey(), values); return ops.add(getKey(), values);
} }
public Set<V> diff(K key) { public Set<V> diff(K key) {
return ops.difference(getKey(), key); return ops.difference(getKey(), key);
} }
public Set<V> diff(Collection<K> keys) { public Set<V> diff(Collection<K> keys) {
return ops.difference(getKey(), keys); return ops.difference(getKey(), keys);
} }
public void diffAndStore(K key, K destKey) { public void diffAndStore(K key, K destKey) {
ops.differenceAndStore(getKey(), key, destKey); ops.differenceAndStore(getKey(), key, destKey);
} }
public void diffAndStore(Collection<K> keys, K destKey) { public void diffAndStore(Collection<K> keys, K destKey) {
ops.differenceAndStore(getKey(), keys, destKey); ops.differenceAndStore(getKey(), keys, destKey);
} }
public RedisOperations<K, V> getOperations() { public RedisOperations<K, V> getOperations() {
return ops.getOperations(); return ops.getOperations();
} }
public Set<V> intersect(K key) { public Set<V> intersect(K key) {
return ops.intersect(getKey(), key); return ops.intersect(getKey(), key);
} }
public Set<V> intersect(Collection<K> keys) { public Set<V> intersect(Collection<K> keys) {
return ops.intersect(getKey(), keys); return ops.intersect(getKey(), keys);
} }
public void intersectAndStore(K key, K destKey) { public void intersectAndStore(K key, K destKey) {
ops.intersectAndStore(getKey(), key, destKey); ops.intersectAndStore(getKey(), key, destKey);
} }
public void intersectAndStore(Collection<K> keys, K destKey) { public void intersectAndStore(Collection<K> keys, K destKey) {
ops.intersectAndStore(getKey(), keys, destKey); ops.intersectAndStore(getKey(), keys, destKey);
} }
public Boolean isMember(Object o) { public Boolean isMember(Object o) {
return ops.isMember(getKey(), o); return ops.isMember(getKey(), o);
} }
public Set<V> members() { public Set<V> members() {
return ops.members(getKey()); return ops.members(getKey());
} }
public Boolean move(K destKey, V value) { public Boolean move(K destKey, V value) {
return ops.move(getKey(), value, destKey); return ops.move(getKey(), value, destKey);
} }
public V randomMember() { public V randomMember() {
return ops.randomMember(getKey()); return ops.randomMember(getKey());
} }
public Set<V> distinctRandomMembers(long count) { public Set<V> distinctRandomMembers(long count) {
return ops.distinctRandomMembers(getKey(), count); return ops.distinctRandomMembers(getKey(), count);
} }
public List<V> randomMembers(long count) { public List<V> randomMembers(long count) {
return ops.randomMembers(getKey(), count); return ops.randomMembers(getKey(), count);
} }
public Long remove(Object... values) { public Long remove(Object... values) {
return ops.remove(getKey(), values); return ops.remove(getKey(), values);
} }
public V pop() { public V pop() {
return ops.pop(getKey()); return ops.pop(getKey());
} }
public Long size() { public Long size() {
return ops.size(getKey()); return ops.size(getKey());
} }
public Set<V> union(K key) { public Set<V> union(K key) {
return ops.union(getKey(), key); return ops.union(getKey(), key);
} }
public Set<V> union(Collection<K> keys) { public Set<V> union(Collection<K> keys) {
return ops.union(getKey(), keys); return ops.union(getKey(), keys);
} }
public void unionAndStore(K key, K destKey) { public void unionAndStore(K key, K destKey) {
ops.unionAndStore(getKey(), key, destKey); ops.unionAndStore(getKey(), key, destKey);
} }
public void unionAndStore(Collection<K> keys, K destKey) { public void unionAndStore(Collection<K> keys, K destKey) {
ops.unionAndStore(getKey(), keys, destKey); ops.unionAndStore(getKey(), keys, destKey);
} }
public DataType getType() { public DataType getType() {
return DataType.SET; return DataType.SET;
} }
} }

View File

@@ -28,7 +28,7 @@ class DefaultBoundValueOperations<K, V> extends DefaultBoundKeyOperations<K> imp
/** /**
* Constructs a new <code>DefaultBoundValueOperations</code> instance. * Constructs a new <code>DefaultBoundValueOperations</code> instance.
* *
* @param key * @param key
* @param operations * @param operations
*/ */
@@ -37,17 +37,14 @@ class DefaultBoundValueOperations<K, V> extends DefaultBoundKeyOperations<K> imp
this.ops = operations.opsForValue(); this.ops = operations.opsForValue();
} }
public V get() { public V get() {
return ops.get(getKey()); return ops.get(getKey());
} }
public V getAndSet(V value) { public V getAndSet(V value) {
return ops.getAndSet(getKey(), value); return ops.getAndSet(getKey(), value);
} }
public Long increment(long delta) { public Long increment(long delta) {
return ops.increment(getKey(), delta); return ops.increment(getKey(), delta);
} }
@@ -60,43 +57,35 @@ class DefaultBoundValueOperations<K, V> extends DefaultBoundKeyOperations<K> imp
return ops.append(getKey(), value); return ops.append(getKey(), value);
} }
public String get(long start, long end) { public String get(long start, long end) {
return ops.get(getKey(), start, end); return ops.get(getKey(), start, end);
} }
public void set(V value, long timeout, TimeUnit unit) { public void set(V value, long timeout, TimeUnit unit) {
ops.set(getKey(), value, timeout, unit); ops.set(getKey(), value, timeout, unit);
} }
public void set(V value) { public void set(V value) {
ops.set(getKey(), value); ops.set(getKey(), value);
} }
public Boolean setIfAbsent(V value) { public Boolean setIfAbsent(V value) {
return ops.setIfAbsent(getKey(), value); return ops.setIfAbsent(getKey(), value);
} }
public void set(V value, long offset) { public void set(V value, long offset) {
ops.set(getKey(), value, offset); ops.set(getKey(), value, offset);
} }
public Long size() { public Long size() {
return ops.size(getKey()); return ops.size(getKey());
} }
public RedisOperations<K, V> getOperations() { public RedisOperations<K, V> getOperations() {
return ops.getOperations(); return ops.getOperations();
} }
public DataType getType() { public DataType getType() {
return DataType.STRING; return DataType.STRING;
} }
} }

View File

@@ -33,7 +33,7 @@ class DefaultBoundZSetOperations<K, V> extends DefaultBoundKeyOperations<K> impl
/** /**
* Constructs a new <code>DefaultBoundZSetOperations</code> instance. * Constructs a new <code>DefaultBoundZSetOperations</code> instance.
* *
* @param key * @param key
* @param oeprations * @param oeprations
*/ */
@@ -42,7 +42,6 @@ class DefaultBoundZSetOperations<K, V> extends DefaultBoundKeyOperations<K> impl
this.ops = operations.opsForZSet(); this.ops = operations.opsForZSet();
} }
public Boolean add(V value, double score) { public Boolean add(V value, double score) {
return ops.add(getKey(), value, score); return ops.add(getKey(), value, score);
} }
@@ -55,113 +54,91 @@ class DefaultBoundZSetOperations<K, V> extends DefaultBoundKeyOperations<K> impl
return ops.incrementScore(getKey(), value, delta); return ops.incrementScore(getKey(), value, delta);
} }
public RedisOperations<K, V> getOperations() { public RedisOperations<K, V> getOperations() {
return ops.getOperations(); return ops.getOperations();
} }
public void intersectAndStore(K otherKey, K destKey) { public void intersectAndStore(K otherKey, K destKey) {
ops.intersectAndStore(getKey(), otherKey, destKey); ops.intersectAndStore(getKey(), otherKey, destKey);
} }
public void intersectAndStore(Collection<K> otherKeys, K destKey) { public void intersectAndStore(Collection<K> otherKeys, K destKey) {
ops.intersectAndStore(getKey(), otherKeys, destKey); ops.intersectAndStore(getKey(), otherKeys, destKey);
} }
public Set<V> range(long start, long end) { public Set<V> range(long start, long end) {
return ops.range(getKey(), start, end); return ops.range(getKey(), start, end);
} }
public Set<V> rangeByScore(double min, double max) { public Set<V> rangeByScore(double min, double max) {
return ops.rangeByScore(getKey(), min, max); return ops.rangeByScore(getKey(), min, max);
} }
public Set<TypedTuple<V>> rangeByScoreWithScores(double min, double max) { public Set<TypedTuple<V>> rangeByScoreWithScores(double min, double max) {
return ops.rangeByScoreWithScores(getKey(), min, max); return ops.rangeByScoreWithScores(getKey(), min, max);
} }
public Set<TypedTuple<V>> rangeWithScores(long start, long end) { public Set<TypedTuple<V>> rangeWithScores(long start, long end) {
return ops.rangeWithScores(getKey(), start, end); return ops.rangeWithScores(getKey(), start, end);
} }
public Set<V> reverseRangeByScore(double min, double max) { public Set<V> reverseRangeByScore(double min, double max) {
return ops.reverseRangeByScore(getKey(), min, max); return ops.reverseRangeByScore(getKey(), min, max);
} }
public Set<TypedTuple<V>> reverseRangeByScoreWithScores(double min, double max) { public Set<TypedTuple<V>> reverseRangeByScoreWithScores(double min, double max) {
return ops.reverseRangeByScoreWithScores(getKey(), min, max); return ops.reverseRangeByScoreWithScores(getKey(), min, max);
} }
public Set<TypedTuple<V>> reverseRangeWithScores(long start, long end) { public Set<TypedTuple<V>> reverseRangeWithScores(long start, long end) {
return ops.reverseRangeWithScores(getKey(), start, end); return ops.reverseRangeWithScores(getKey(), start, end);
} }
public Long rank(Object o) { public Long rank(Object o) {
return ops.rank(getKey(), o); return ops.rank(getKey(), o);
} }
public Long reverseRank(Object o) { public Long reverseRank(Object o) {
return ops.reverseRank(getKey(), o); return ops.reverseRank(getKey(), o);
} }
public Double score(Object o) { public Double score(Object o) {
return ops.score(getKey(), o); return ops.score(getKey(), o);
} }
public Long remove(Object... values) { public Long remove(Object... values) {
return ops.remove(getKey(), values); return ops.remove(getKey(), values);
} }
public void removeRange(long start, long end) { public void removeRange(long start, long end) {
ops.removeRange(getKey(), start, end); ops.removeRange(getKey(), start, end);
} }
public void removeRangeByScore(double min, double max) { public void removeRangeByScore(double min, double max) {
ops.removeRangeByScore(getKey(), min, max); ops.removeRangeByScore(getKey(), min, max);
} }
public Set<V> reverseRange(long start, long end) { public Set<V> reverseRange(long start, long end) {
return ops.reverseRange(getKey(), start, end); return ops.reverseRange(getKey(), start, end);
} }
public Long count(double min, double max) { public Long count(double min, double max) {
return ops.count(getKey(), min, max); return ops.count(getKey(), min, max);
} }
public Long size() { public Long size() {
return ops.size(getKey()); return ops.size(getKey());
} }
public void unionAndStore(K otherKey, K destKey) { public void unionAndStore(K otherKey, K destKey) {
ops.unionAndStore(getKey(), otherKey, destKey); ops.unionAndStore(getKey(), otherKey, destKey);
} }
public void unionAndStore(Collection<K> otherKeys, K destKey) { public void unionAndStore(Collection<K> otherKeys, K destKey) {
ops.unionAndStore(getKey(), otherKeys, destKey); ops.unionAndStore(getKey(), otherKeys, destKey);
} }
public DataType getType() { public DataType getType() {
return DataType.ZSET; return DataType.ZSET;
} }
} }

View File

@@ -26,7 +26,7 @@ import org.springframework.data.redis.connection.RedisConnection;
/** /**
* Default implementation of {@link HashOperations}. * Default implementation of {@link HashOperations}.
* *
* @author Costin Leau * @author Costin Leau
*/ */
class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> implements HashOperations<K, HK, HV> { class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> implements HashOperations<K, HK, HV> {
@@ -37,13 +37,12 @@ class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> imp
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public HV get(K key, Object hashKey) { public HV get(K key, Object hashKey) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawHashKey = rawHashKey(hashKey); final byte[] rawHashKey = rawHashKey(hashKey);
byte[] rawHashValue = execute(new RedisCallback<byte[]>() { byte[] rawHashValue = execute(new RedisCallback<byte[]>() {
public byte[] doInRedis(RedisConnection connection) { public byte[] doInRedis(RedisConnection connection) {
return connection.hGet(rawKey, rawHashKey); return connection.hGet(rawKey, rawHashKey);
} }
@@ -52,26 +51,24 @@ class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> imp
return (HV) deserializeHashValue(rawHashValue); return (HV) deserializeHashValue(rawHashValue);
} }
public Boolean hasKey(K key, Object hashKey) { public Boolean hasKey(K key, Object hashKey) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawHashKey = rawHashKey(hashKey); final byte[] rawHashKey = rawHashKey(hashKey);
return execute(new RedisCallback<Boolean>() { return execute(new RedisCallback<Boolean>() {
public Boolean doInRedis(RedisConnection connection) { public Boolean doInRedis(RedisConnection connection) {
return connection.hExists(rawKey, rawHashKey); return connection.hExists(rawKey, rawHashKey);
} }
}, true); }, true);
} }
public Long increment(K key, HK hashKey, final long delta) { public Long increment(K key, HK hashKey, final long delta) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawHashKey = rawHashKey(hashKey); final byte[] rawHashKey = rawHashKey(hashKey);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.hIncrBy(rawKey, rawHashKey, delta); return connection.hIncrBy(rawKey, rawHashKey, delta);
} }
@@ -94,7 +91,7 @@ class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> imp
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() { Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
public Set<byte[]> doInRedis(RedisConnection connection) { public Set<byte[]> doInRedis(RedisConnection connection) {
return connection.hKeys(rawKey); return connection.hKeys(rawKey);
} }
@@ -103,19 +100,17 @@ class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> imp
return deserializeHashKeys(rawValues); return deserializeHashKeys(rawValues);
} }
public Long size(K key) { public Long size(K key) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.hLen(rawKey); return connection.hLen(rawKey);
} }
}, true); }, true);
} }
public void putAll(K key, Map<? extends HK, ? extends HV> m) { public void putAll(K key, Map<? extends HK, ? extends HV> m) {
if (m.isEmpty()) { if (m.isEmpty()) {
return; return;
@@ -130,7 +125,7 @@ class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> imp
} }
execute(new RedisCallback<Object>() { execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection) { public Object doInRedis(RedisConnection connection) {
connection.hMSet(rawKey, hashes); connection.hMSet(rawKey, hashes);
return null; return null;
@@ -138,8 +133,6 @@ class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> imp
}, true); }, true);
} }
public List<HV> multiGet(K key, Collection<HK> fields) { public List<HV> multiGet(K key, Collection<HK> fields) {
if (fields.isEmpty()) { if (fields.isEmpty()) {
return Collections.emptyList(); return Collections.emptyList();
@@ -155,7 +148,7 @@ class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> imp
} }
List<byte[]> rawValues = execute(new RedisCallback<List<byte[]>>() { List<byte[]> rawValues = execute(new RedisCallback<List<byte[]>>() {
public List<byte[]> doInRedis(RedisConnection connection) { public List<byte[]> doInRedis(RedisConnection connection) {
return connection.hMGet(rawKey, rawHashKeys); return connection.hMGet(rawKey, rawHashKeys);
} }
@@ -164,14 +157,13 @@ class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> imp
return deserializeHashValues(rawValues); return deserializeHashValues(rawValues);
} }
public void put(K key, HK hashKey, HV value) { public void put(K key, HK hashKey, HV value) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawHashKey = rawHashKey(hashKey); final byte[] rawHashKey = rawHashKey(hashKey);
final byte[] rawHashValue = rawHashValue(value); final byte[] rawHashValue = rawHashValue(value);
execute(new RedisCallback<Object>() { execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection) { public Object doInRedis(RedisConnection connection) {
connection.hSet(rawKey, rawHashKey, rawHashValue); connection.hSet(rawKey, rawHashKey, rawHashValue);
return null; return null;
@@ -179,27 +171,24 @@ class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> imp
}, true); }, true);
} }
public Boolean putIfAbsent(K key, HK hashKey, HV value) { public Boolean putIfAbsent(K key, HK hashKey, HV value) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawHashKey = rawHashKey(hashKey); final byte[] rawHashKey = rawHashKey(hashKey);
final byte[] rawHashValue = rawHashValue(value); final byte[] rawHashValue = rawHashValue(value);
return execute(new RedisCallback<Boolean>() { return execute(new RedisCallback<Boolean>() {
public Boolean doInRedis(RedisConnection connection) { public Boolean doInRedis(RedisConnection connection) {
return connection.hSetNX(rawKey, rawHashKey, rawHashValue); return connection.hSetNX(rawKey, rawHashKey, rawHashValue);
} }
}, true); }, true);
} }
public List<HV> values(K key) { public List<HV> values(K key) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
List<byte[]> rawValues = execute(new RedisCallback<List<byte[]>>() { List<byte[]> rawValues = execute(new RedisCallback<List<byte[]>>() {
public List<byte[]> doInRedis(RedisConnection connection) { public List<byte[]> doInRedis(RedisConnection connection) {
return connection.hVals(rawKey); return connection.hVals(rawKey);
} }
@@ -208,13 +197,12 @@ class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> imp
return deserializeHashValues(rawValues); return deserializeHashValues(rawValues);
} }
public void delete(K key, Object... hashKeys) { public void delete(K key, Object... hashKeys) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[][] rawHashKeys = rawHashKeys(hashKeys); final byte[][] rawHashKeys = rawHashKeys(hashKeys);
execute(new RedisCallback<Object>() { execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection) { public Object doInRedis(RedisConnection connection) {
connection.hDel(rawKey, rawHashKeys); connection.hDel(rawKey, rawHashKeys);
return null; return null;
@@ -222,12 +210,11 @@ class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> imp
}, true); }, true);
} }
public Map<HK, HV> entries(K key) { public Map<HK, HV> entries(K key) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
Map<byte[], byte[]> entries = execute(new RedisCallback<Map<byte[], byte[]>>() { Map<byte[], byte[]> entries = execute(new RedisCallback<Map<byte[], byte[]>>() {
public Map<byte[], byte[]> doInRedis(RedisConnection connection) { public Map<byte[], byte[]> doInRedis(RedisConnection connection) {
return connection.hGetAll(rawKey); return connection.hGetAll(rawKey);
} }
@@ -235,4 +222,4 @@ class DefaultHashOperations<K, HK, HV> extends AbstractOperations<K, Object> imp
return deserializeHashMap(entries); return deserializeHashMap(entries);
} }
} }

View File

@@ -33,30 +33,28 @@ class DefaultListOperations<K, V> extends AbstractOperations<K, V> implements Li
super(template); super(template);
} }
public V index(K key, final long index) { public V index(K key, final long index) {
return execute(new ValueDeserializingRedisCallback(key) { return execute(new ValueDeserializingRedisCallback(key) {
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
return connection.lIndex(rawKey, index); return connection.lIndex(rawKey, index);
} }
}, true); }, true);
} }
public V leftPop(K key) { public V leftPop(K key) {
return execute(new ValueDeserializingRedisCallback(key) { return execute(new ValueDeserializingRedisCallback(key) {
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
return connection.lPop(rawKey); return connection.lPop(rawKey);
} }
}, true); }, true);
} }
public V leftPop(K key, long timeout, TimeUnit unit) { public V leftPop(K key, long timeout, TimeUnit unit) {
final int tm = (int) TimeoutUtils.toSeconds(timeout, unit); final int tm = (int) TimeoutUtils.toSeconds(timeout, unit);
return execute(new ValueDeserializingRedisCallback(key) { return execute(new ValueDeserializingRedisCallback(key) {
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
List<byte[]> lPop = connection.bLPop(tm, rawKey); List<byte[]> lPop = connection.bLPop(tm, rawKey);
return (CollectionUtils.isEmpty(lPop) ? null : lPop.get(1)); return (CollectionUtils.isEmpty(lPop) ? null : lPop.get(1));
@@ -64,12 +62,11 @@ class DefaultListOperations<K, V> extends AbstractOperations<K, V> implements Li
}, true); }, true);
} }
public Long leftPush(K key, V value) { public Long leftPush(K key, V value) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value); final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.lPush(rawKey, rawValue); return connection.lPush(rawKey, rawValue);
} }
@@ -90,38 +87,35 @@ class DefaultListOperations<K, V> extends AbstractOperations<K, V> implements Li
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value); final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.lPushX(rawKey, rawValue); return connection.lPushX(rawKey, rawValue);
} }
}, true); }, true);
} }
public Long leftPush(K key, V pivot, V value) { public Long leftPush(K key, V pivot, V value) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawPivot = rawValue(pivot); final byte[] rawPivot = rawValue(pivot);
final byte[] rawValue = rawValue(value); final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.lInsert(rawKey, Position.BEFORE, rawPivot, rawValue); return connection.lInsert(rawKey, Position.BEFORE, rawPivot, rawValue);
} }
}, true); }, true);
} }
public Long size(K key) { public Long size(K key) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.lLen(rawKey); return connection.lLen(rawKey);
} }
}, true); }, true);
} }
public List<V> range(K key, final long start, final long end) { public List<V> range(K key, final long start, final long end) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<List<V>>() { return execute(new RedisCallback<List<V>>() {
@@ -131,34 +125,31 @@ class DefaultListOperations<K, V> extends AbstractOperations<K, V> implements Li
}, true); }, true);
} }
public Long remove(K key, final long count, Object value) { public Long remove(K key, final long count, Object value) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value); final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.lRem(rawKey, count, rawValue); return connection.lRem(rawKey, count, rawValue);
} }
}, true); }, true);
} }
public V rightPop(K key) { public V rightPop(K key) {
return execute(new ValueDeserializingRedisCallback(key) { return execute(new ValueDeserializingRedisCallback(key) {
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
return connection.rPop(rawKey); return connection.rPop(rawKey);
} }
}, true); }, true);
} }
public V rightPop(K key, long timeout, TimeUnit unit) { public V rightPop(K key, long timeout, TimeUnit unit) {
final int tm = (int) TimeoutUtils.toSeconds(timeout, unit); final int tm = (int) TimeoutUtils.toSeconds(timeout, unit);
return execute(new ValueDeserializingRedisCallback(key) { return execute(new ValueDeserializingRedisCallback(key) {
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
List<byte[]> bRPop = connection.bRPop(tm, rawKey); List<byte[]> bRPop = connection.bRPop(tm, rawKey);
return (CollectionUtils.isEmpty(bRPop) ? null : bRPop.get(1)); return (CollectionUtils.isEmpty(bRPop) ? null : bRPop.get(1));
@@ -166,12 +157,11 @@ class DefaultListOperations<K, V> extends AbstractOperations<K, V> implements Li
}, true); }, true);
} }
public Long rightPush(K key, V value) { public Long rightPush(K key, V value) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value); final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.rPush(rawKey, rawValue); return connection.rPush(rawKey, rawValue);
} }
@@ -192,57 +182,53 @@ class DefaultListOperations<K, V> extends AbstractOperations<K, V> implements Li
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value); final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.rPushX(rawKey, rawValue); return connection.rPushX(rawKey, rawValue);
} }
}, true); }, true);
} }
public Long rightPush(K key, V pivot, V value) { public Long rightPush(K key, V pivot, V value) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawPivot = rawValue(pivot); final byte[] rawPivot = rawValue(pivot);
final byte[] rawValue = rawValue(value); final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.lInsert(rawKey, Position.AFTER, rawPivot, rawValue); return connection.lInsert(rawKey, Position.AFTER, rawPivot, rawValue);
} }
}, true); }, true);
} }
public V rightPopAndLeftPush(K sourceKey, K destinationKey) { public V rightPopAndLeftPush(K sourceKey, K destinationKey) {
final byte[] rawDestKey = rawKey(destinationKey); final byte[] rawDestKey = rawKey(destinationKey);
return execute(new ValueDeserializingRedisCallback(sourceKey) { return execute(new ValueDeserializingRedisCallback(sourceKey) {
protected byte[] inRedis(byte[] rawSourceKey, RedisConnection connection) { protected byte[] inRedis(byte[] rawSourceKey, RedisConnection connection) {
return connection.rPopLPush(rawSourceKey, rawDestKey); return connection.rPopLPush(rawSourceKey, rawDestKey);
} }
}, true); }, true);
} }
public V rightPopAndLeftPush(K sourceKey, K destinationKey, long timeout, TimeUnit unit) { public V rightPopAndLeftPush(K sourceKey, K destinationKey, long timeout, TimeUnit unit) {
final int tm = (int)TimeoutUtils.toSeconds(timeout, unit); final int tm = (int) TimeoutUtils.toSeconds(timeout, unit);
final byte[] rawDestKey = rawKey(destinationKey); final byte[] rawDestKey = rawKey(destinationKey);
return execute(new ValueDeserializingRedisCallback(sourceKey) { return execute(new ValueDeserializingRedisCallback(sourceKey) {
protected byte[] inRedis(byte[] rawSourceKey, RedisConnection connection) { protected byte[] inRedis(byte[] rawSourceKey, RedisConnection connection) {
return connection.bRPopLPush(tm, rawSourceKey, rawDestKey); return connection.bRPopLPush(tm, rawSourceKey, rawDestKey);
} }
}, true); }, true);
} }
public void set(K key, final long index, V value) { public void set(K key, final long index, V value) {
final byte[] rawValue = rawValue(value); final byte[] rawValue = rawValue(value);
execute(new ValueDeserializingRedisCallback(key) { execute(new ValueDeserializingRedisCallback(key) {
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
connection.lSet(rawKey, index, rawValue); connection.lSet(rawKey, index, rawValue);
return null; return null;
@@ -250,14 +236,13 @@ class DefaultListOperations<K, V> extends AbstractOperations<K, V> implements Li
}, true); }, true);
} }
public void trim(K key, final long start, final long end) { public void trim(K key, final long start, final long end) {
execute(new ValueDeserializingRedisCallback(key) { execute(new ValueDeserializingRedisCallback(key) {
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
connection.lTrim(rawKey, start, end); connection.lTrim(rawKey, start, end);
return null; return null;
} }
}, true); }, true);
} }
} }

View File

@@ -25,7 +25,7 @@ import org.springframework.data.redis.connection.RedisConnection;
/** /**
* Default implementation of {@link SetOperations}. * Default implementation of {@link SetOperations}.
* *
* @author Costin Leau * @author Costin Leau
*/ */
class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements SetOperations<K, V> { class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements SetOperations<K, V> {
@@ -34,19 +34,17 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
super(template); super(template);
} }
public Long add(K key, V... values) { public Long add(K key, V... values) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[][] rawValues = rawValues(values); final byte[][] rawValues = rawValues(values);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.sAdd(rawKey, rawValues); return connection.sAdd(rawKey, rawValues);
} }
}, true); }, true);
} }
public Set<V> difference(K key, K otherKey) { public Set<V> difference(K key, K otherKey) {
return difference(key, Collections.singleton(otherKey)); return difference(key, Collections.singleton(otherKey));
} }
@@ -54,7 +52,7 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
public Set<V> difference(final K key, final Collection<K> otherKeys) { public Set<V> difference(final K key, final Collection<K> otherKeys) {
final byte[][] rawKeys = rawKeys(key, otherKeys); final byte[][] rawKeys = rawKeys(key, otherKeys);
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() { Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
public Set<byte[]> doInRedis(RedisConnection connection) { public Set<byte[]> doInRedis(RedisConnection connection) {
return connection.sDiff(rawKeys); return connection.sDiff(rawKeys);
} }
@@ -63,24 +61,21 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
return deserializeValues(rawValues); return deserializeValues(rawValues);
} }
public Long differenceAndStore(K key, K otherKey, K destKey) { public Long differenceAndStore(K key, K otherKey, K destKey) {
return differenceAndStore(key, Collections.singleton(otherKey), destKey); return differenceAndStore(key, Collections.singleton(otherKey), destKey);
} }
public Long differenceAndStore(final K key, final Collection<K> otherKeys, K destKey) { public Long differenceAndStore(final K key, final Collection<K> otherKeys, K destKey) {
final byte[][] rawKeys = rawKeys(key, otherKeys); final byte[][] rawKeys = rawKeys(key, otherKeys);
final byte[] rawDestKey = rawKey(destKey); final byte[] rawDestKey = rawKey(destKey);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.sDiffStore(rawDestKey, rawKeys); return connection.sDiffStore(rawDestKey, rawKeys);
} }
}, true); }, true);
} }
public Set<V> intersect(K key, K otherKey) { public Set<V> intersect(K key, K otherKey) {
return intersect(key, Collections.singleton(otherKey)); return intersect(key, Collections.singleton(otherKey));
} }
@@ -88,7 +83,7 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
public Set<V> intersect(K key, Collection<K> otherKeys) { public Set<V> intersect(K key, Collection<K> otherKeys) {
final byte[][] rawKeys = rawKeys(key, otherKeys); final byte[][] rawKeys = rawKeys(key, otherKeys);
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() { Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
public Set<byte[]> doInRedis(RedisConnection connection) { public Set<byte[]> doInRedis(RedisConnection connection) {
return connection.sInter(rawKeys); return connection.sInter(rawKeys);
} }
@@ -97,17 +92,15 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
return deserializeValues(rawValues); return deserializeValues(rawValues);
} }
public Long intersectAndStore(K key, K otherKey, K destKey) { public Long intersectAndStore(K key, K otherKey, K destKey) {
return intersectAndStore(key, Collections.singleton(otherKey), destKey); return intersectAndStore(key, Collections.singleton(otherKey), destKey);
} }
public Long intersectAndStore(K key, Collection<K> otherKeys, K destKey) { public Long intersectAndStore(K key, Collection<K> otherKeys, K destKey) {
final byte[][] rawKeys = rawKeys(key, otherKeys); final byte[][] rawKeys = rawKeys(key, otherKeys);
final byte[] rawDestKey = rawKey(destKey); final byte[] rawDestKey = rawKey(destKey);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
connection.sInterStore(rawDestKey, rawKeys); connection.sInterStore(rawDestKey, rawKeys);
return null; return null;
@@ -115,12 +108,11 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
}, true); }, true);
} }
public Boolean isMember(K key, Object o) { public Boolean isMember(K key, Object o) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(o); final byte[] rawValue = rawValue(o);
return execute(new RedisCallback<Boolean>() { return execute(new RedisCallback<Boolean>() {
public Boolean doInRedis(RedisConnection connection) { public Boolean doInRedis(RedisConnection connection) {
return connection.sIsMember(rawKey, rawValue); return connection.sIsMember(rawKey, rawValue);
} }
@@ -130,7 +122,7 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
public Set<V> members(K key) { public Set<V> members(K key) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() { Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
public Set<byte[]> doInRedis(RedisConnection connection) { public Set<byte[]> doInRedis(RedisConnection connection) {
return connection.sMembers(rawKey); return connection.sMembers(rawKey);
} }
@@ -139,36 +131,33 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
return deserializeValues(rawValues); return deserializeValues(rawValues);
} }
public Boolean move(K key, V value, K destKey) { public Boolean move(K key, V value, K destKey) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawDestKey = rawKey(destKey); final byte[] rawDestKey = rawKey(destKey);
final byte[] rawValue = rawValue(value); final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Boolean>() { return execute(new RedisCallback<Boolean>() {
public Boolean doInRedis(RedisConnection connection) { public Boolean doInRedis(RedisConnection connection) {
return connection.sMove(rawKey, rawDestKey, rawValue); return connection.sMove(rawKey, rawDestKey, rawValue);
} }
}, true); }, true);
} }
public V randomMember(K key) { public V randomMember(K key) {
return execute(new ValueDeserializingRedisCallback(key) { return execute(new ValueDeserializingRedisCallback(key) {
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
return connection.sRandMember(rawKey); return connection.sRandMember(rawKey);
} }
}, true); }, true);
} }
public Set<V> distinctRandomMembers(K key, final long count) { public Set<V> distinctRandomMembers(K key, final long count) {
if(count < 0) { if (count < 0) {
throw new IllegalArgumentException("Negative count not supported. " + throw new IllegalArgumentException("Negative count not supported. "
"Use randomMembers to allow duplicate elements."); + "Use randomMembers to allow duplicate elements.");
} }
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() { Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
@@ -179,57 +168,52 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
return deserializeValues(rawValues); return deserializeValues(rawValues);
} }
public List<V> randomMembers(K key, final long count) { public List<V> randomMembers(K key, final long count) {
if(count < 0) { if (count < 0) {
throw new IllegalArgumentException("Use a positive number for count. " + throw new IllegalArgumentException("Use a positive number for count. "
"This method is already allowing duplicate elements."); + "This method is already allowing duplicate elements.");
} }
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
List<byte[]> rawValues = execute(new RedisCallback<List<byte[]>>() { List<byte[]> rawValues = execute(new RedisCallback<List<byte[]>>() {
public List<byte[]> doInRedis(RedisConnection connection) { public List<byte[]> doInRedis(RedisConnection connection) {
return connection.sRandMember(rawKey, - count); return connection.sRandMember(rawKey, -count);
} }
}, true); }, true);
return deserializeValues(rawValues); return deserializeValues(rawValues);
} }
public Long remove(K key, Object... values) { public Long remove(K key, Object... values) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[][] rawValues = rawValues(values); final byte[][] rawValues = rawValues(values);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.sRem(rawKey, rawValues); return connection.sRem(rawKey, rawValues);
} }
}, true); }, true);
} }
public V pop(K key) { public V pop(K key) {
return execute(new ValueDeserializingRedisCallback(key) { return execute(new ValueDeserializingRedisCallback(key) {
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
return connection.sPop(rawKey); return connection.sPop(rawKey);
} }
}, true); }, true);
} }
public Long size(K key) { public Long size(K key) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.sCard(rawKey); return connection.sCard(rawKey);
} }
}, true); }, true);
} }
public Set<V> union(K key, K otherKey) { public Set<V> union(K key, K otherKey) {
return union(key, Collections.singleton(otherKey)); return union(key, Collections.singleton(otherKey));
} }
@@ -237,7 +221,7 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
public Set<V> union(K key, Collection<K> otherKeys) { public Set<V> union(K key, Collection<K> otherKeys) {
final byte[][] rawKeys = rawKeys(key, otherKeys); final byte[][] rawKeys = rawKeys(key, otherKeys);
Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() { Set<byte[]> rawValues = execute(new RedisCallback<Set<byte[]>>() {
public Set<byte[]> doInRedis(RedisConnection connection) { public Set<byte[]> doInRedis(RedisConnection connection) {
return connection.sUnion(rawKeys); return connection.sUnion(rawKeys);
} }
@@ -246,20 +230,18 @@ class DefaultSetOperations<K, V> extends AbstractOperations<K, V> implements Set
return deserializeValues(rawValues); return deserializeValues(rawValues);
} }
public Long unionAndStore(K key, K otherKey, K destKey) { public Long unionAndStore(K key, K otherKey, K destKey) {
return unionAndStore(key, Collections.singleton(otherKey), destKey); return unionAndStore(key, Collections.singleton(otherKey), destKey);
} }
public Long unionAndStore(K key, Collection<K> otherKeys, K destKey) { public Long unionAndStore(K key, Collection<K> otherKeys, K destKey) {
final byte[][] rawKeys = rawKeys(key, otherKeys); final byte[][] rawKeys = rawKeys(key, otherKeys);
final byte[] rawDestKey = rawKey(destKey); final byte[] rawDestKey = rawKey(destKey);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.sUnionStore(rawDestKey, rawKeys); return connection.sUnionStore(rawDestKey, rawKeys);
} }
}, true); }, true);
} }
} }

View File

@@ -31,7 +31,7 @@ public class DefaultTypedTuple<V> implements TypedTuple<V> {
/** /**
* Constructs a new <code>DefaultTypedTuple</code> instance. * Constructs a new <code>DefaultTypedTuple</code> instance.
* *
* @param value * @param value
* @param score * @param score
*/ */
@@ -40,17 +40,14 @@ public class DefaultTypedTuple<V> implements TypedTuple<V> {
this.value = value; this.value = value;
} }
public Double getScore() { public Double getScore() {
return score; return score;
} }
public V getValue() { public V getValue() {
return value; return value;
} }
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
@@ -59,7 +56,6 @@ public class DefaultTypedTuple<V> implements TypedTuple<V> {
return result; return result;
} }
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) if (this == obj)
return true; return true;
@@ -71,27 +67,24 @@ public class DefaultTypedTuple<V> implements TypedTuple<V> {
if (score == null) { if (score == null) {
if (other.score != null) if (other.score != null)
return false; return false;
} } else if (!score.equals(other.score))
else if (!score.equals(other.score))
return false; return false;
if (value == null) { if (value == null) {
if (other.value != null) if (other.value != null)
return false; return false;
} } else if (value instanceof byte[]) {
else if(value instanceof byte[]) { if (!(other.value instanceof byte[])) {
if(!(other.value instanceof byte[])) {
return false; return false;
} }
return Arrays.equals((byte[])value, (byte[])other.value); return Arrays.equals((byte[]) value, (byte[]) other.value);
} else if (!value.equals(other.value)) } else if (!value.equals(other.value))
return false; return false;
return true; return true;
} }
public int compareTo(Double o) { public int compareTo(Double o) {
Double d = (score == null ? Double.valueOf(0) : score); Double d = (score == null ? Double.valueOf(0) : score);
Double a = (o == null ? Double.valueOf(0) : o); Double a = (o == null ? Double.valueOf(0) : o);
return d.compareTo(a); return d.compareTo(a);
} }
} }

View File

@@ -37,39 +37,36 @@ class DefaultValueOperations<K, V> extends AbstractOperations<K, V> implements V
super(template); super(template);
} }
public V get(final Object key) { public V get(final Object key) {
return execute(new ValueDeserializingRedisCallback(key) { return execute(new ValueDeserializingRedisCallback(key) {
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
return connection.get(rawKey); return connection.get(rawKey);
} }
}, true); }, true);
} }
public V getAndSet(K key, V newValue) { public V getAndSet(K key, V newValue) {
final byte[] rawValue = rawValue(newValue); final byte[] rawValue = rawValue(newValue);
return execute(new ValueDeserializingRedisCallback(key) { return execute(new ValueDeserializingRedisCallback(key) {
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
return connection.getSet(rawKey, rawValue); return connection.getSet(rawKey, rawValue);
} }
}, true); }, true);
} }
public Long increment(K key, final long delta) { public Long increment(K key, final long delta) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.incrBy(rawKey, delta); return connection.incrBy(rawKey, delta);
} }
}, true); }, true);
} }
public Double increment(K key, final double delta) { public Double increment(K key, final double delta) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Double>() { return execute(new RedisCallback<Double>() {
@@ -84,19 +81,18 @@ class DefaultValueOperations<K, V> extends AbstractOperations<K, V> implements V
final byte[] rawString = rawString(value); final byte[] rawString = rawString(value);
return execute(new RedisCallback<Integer>() { return execute(new RedisCallback<Integer>() {
public Integer doInRedis(RedisConnection connection) { public Integer doInRedis(RedisConnection connection) {
return connection.append(rawKey, rawString).intValue(); return connection.append(rawKey, rawString).intValue();
} }
}, true); }, true);
} }
public String get(K key, final long start, final long end) { public String get(K key, final long start, final long end) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
byte[] rawReturn = execute(new RedisCallback<byte[]>() { byte[] rawReturn = execute(new RedisCallback<byte[]>() {
public byte[] doInRedis(RedisConnection connection) { public byte[] doInRedis(RedisConnection connection) {
return connection.getRange(rawKey, start, end); return connection.getRange(rawKey, start, end);
} }
@@ -118,7 +114,7 @@ class DefaultValueOperations<K, V> extends AbstractOperations<K, V> implements V
} }
List<byte[]> rawValues = execute(new RedisCallback<List<byte[]>>() { List<byte[]> rawValues = execute(new RedisCallback<List<byte[]>>() {
public List<byte[]> doInRedis(RedisConnection connection) { public List<byte[]> doInRedis(RedisConnection connection) {
return connection.mGet(rawKeys); return connection.mGet(rawKeys);
} }
@@ -127,7 +123,6 @@ class DefaultValueOperations<K, V> extends AbstractOperations<K, V> implements V
return deserializeValues(rawValues); return deserializeValues(rawValues);
} }
public void multiSet(Map<? extends K, ? extends V> m) { public void multiSet(Map<? extends K, ? extends V> m) {
if (m.isEmpty()) { if (m.isEmpty()) {
return; return;
@@ -140,7 +135,7 @@ class DefaultValueOperations<K, V> extends AbstractOperations<K, V> implements V
} }
execute(new RedisCallback<Object>() { execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection) { public Object doInRedis(RedisConnection connection) {
connection.mSet(rawKeys); connection.mSet(rawKeys);
return null; return null;
@@ -148,7 +143,6 @@ class DefaultValueOperations<K, V> extends AbstractOperations<K, V> implements V
}, true); }, true);
} }
public Boolean multiSetIfAbsent(Map<? extends K, ? extends V> m) { public Boolean multiSetIfAbsent(Map<? extends K, ? extends V> m) {
if (m.isEmpty()) { if (m.isEmpty()) {
return true; return true;
@@ -161,18 +155,17 @@ class DefaultValueOperations<K, V> extends AbstractOperations<K, V> implements V
} }
return execute(new RedisCallback<Boolean>() { return execute(new RedisCallback<Boolean>() {
public Boolean doInRedis(RedisConnection connection) { public Boolean doInRedis(RedisConnection connection) {
return connection.mSetNX(rawKeys); return connection.mSetNX(rawKeys);
} }
}, true); }, true);
} }
public void set(K key, V value) { public void set(K key, V value) {
final byte[] rawValue = rawValue(value); final byte[] rawValue = rawValue(value);
execute(new ValueDeserializingRedisCallback(key) { execute(new ValueDeserializingRedisCallback(key) {
protected byte[] inRedis(byte[] rawKey, RedisConnection connection) { protected byte[] inRedis(byte[] rawKey, RedisConnection connection) {
connection.set(rawKey, rawValue); connection.set(rawKey, rawValue);
return null; return null;
@@ -180,14 +173,13 @@ class DefaultValueOperations<K, V> extends AbstractOperations<K, V> implements V
}, true); }, true);
} }
public void set(K key, V value, long timeout, TimeUnit unit) { public void set(K key, V value, long timeout, TimeUnit unit) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value); final byte[] rawValue = rawValue(value);
final long rawTimeout = TimeoutUtils.toSeconds(timeout, unit); final long rawTimeout = TimeoutUtils.toSeconds(timeout, unit);
execute(new RedisCallback<Object>() { execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection) throws DataAccessException { public Object doInRedis(RedisConnection connection) throws DataAccessException {
connection.setEx(rawKey, rawTimeout, rawValue); connection.setEx(rawKey, rawTimeout, rawValue);
return null; return null;
@@ -195,27 +187,24 @@ class DefaultValueOperations<K, V> extends AbstractOperations<K, V> implements V
}, true); }, true);
} }
public Boolean setIfAbsent(K key, V value) { public Boolean setIfAbsent(K key, V value) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value); final byte[] rawValue = rawValue(value);
return execute(new RedisCallback<Boolean>() { return execute(new RedisCallback<Boolean>() {
public Boolean doInRedis(RedisConnection connection) throws DataAccessException { public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
return connection.setNX(rawKey, rawValue); return connection.setNX(rawKey, rawValue);
} }
}, true); }, true);
} }
public void set(K key, final V value, final long offset) { public void set(K key, final V value, final long offset) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value); final byte[] rawValue = rawValue(value);
execute(new RedisCallback<Object>() { execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection) { public Object doInRedis(RedisConnection connection) {
connection.setRange(rawKey, rawValue, offset); connection.setRange(rawKey, rawValue, offset);
return null; return null;
@@ -223,15 +212,14 @@ class DefaultValueOperations<K, V> extends AbstractOperations<K, V> implements V
}, true); }, true);
} }
public Long size(K key) { public Long size(K key) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
public Long doInRedis(RedisConnection connection) { public Long doInRedis(RedisConnection connection) {
return connection.strLen(rawKey); return connection.strLen(rawKey);
} }
}, true); }, true);
} }
} }

View File

@@ -33,7 +33,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
super(template); super(template);
} }
public Boolean add(final K key, final V value, final double score) { public Boolean add(final K key, final V value, final double score) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(value); final byte[] rawValue = rawValue(value);
@@ -70,12 +69,10 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
}, true); }, true);
} }
public Long intersectAndStore(K key, K otherKey, K destKey) { public Long intersectAndStore(K key, K otherKey, K destKey) {
return intersectAndStore(key, Collections.singleton(otherKey), destKey); return intersectAndStore(key, Collections.singleton(otherKey), destKey);
} }
public Long intersectAndStore(K key, Collection<K> otherKeys, K destKey) { public Long intersectAndStore(K key, Collection<K> otherKeys, K destKey) {
final byte[][] rawKeys = rawKeys(key, otherKeys); final byte[][] rawKeys = rawKeys(key, otherKeys);
final byte[] rawDestKey = rawKey(destKey); final byte[] rawDestKey = rawKey(destKey);
@@ -87,7 +84,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
}, true); }, true);
} }
public Set<V> range(K key, final long start, final long end) { public Set<V> range(K key, final long start, final long end) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
@@ -101,7 +97,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
return deserializeValues(rawValues); return deserializeValues(rawValues);
} }
public Set<V> reverseRange(K key, final long start, final long end) { public Set<V> reverseRange(K key, final long start, final long end) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
@@ -115,7 +110,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
return deserializeValues(rawValues); return deserializeValues(rawValues);
} }
public Set<TypedTuple<V>> rangeWithScores(K key, final long start, final long end) { public Set<TypedTuple<V>> rangeWithScores(K key, final long start, final long end) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
@@ -129,7 +123,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
return deserializeTupleValues(rawValues); return deserializeTupleValues(rawValues);
} }
public Set<TypedTuple<V>> reverseRangeWithScores(K key, final long start, final long end) { public Set<TypedTuple<V>> reverseRangeWithScores(K key, final long start, final long end) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
@@ -143,7 +136,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
return deserializeTupleValues(rawValues); return deserializeTupleValues(rawValues);
} }
public Set<V> rangeByScore(K key, final double min, final double max) { public Set<V> rangeByScore(K key, final double min, final double max) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
@@ -170,7 +162,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
return deserializeValues(rawValues); return deserializeValues(rawValues);
} }
public Set<V> reverseRangeByScore(K key, final double min, final double max) { public Set<V> reverseRangeByScore(K key, final double min, final double max) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
@@ -210,7 +201,8 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
return deserializeTupleValues(rawValues); return deserializeTupleValues(rawValues);
} }
public Set<TypedTuple<V>> rangeByScoreWithScores(K key, final double min, final double max, final long offset, final long count) { public Set<TypedTuple<V>> rangeByScoreWithScores(K key, final double min, final double max, final long offset,
final long count) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
Set<Tuple> rawValues = execute(new RedisCallback<Set<Tuple>>() { Set<Tuple> rawValues = execute(new RedisCallback<Set<Tuple>>() {
@@ -223,7 +215,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
return deserializeTupleValues(rawValues); return deserializeTupleValues(rawValues);
} }
public Set<TypedTuple<V>> reverseRangeByScoreWithScores(K key, final double min, final double max) { public Set<TypedTuple<V>> reverseRangeByScoreWithScores(K key, final double min, final double max) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
@@ -238,7 +229,8 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
return deserializeTupleValues(rawValues); return deserializeTupleValues(rawValues);
} }
public Set<TypedTuple<V>> reverseRangeByScoreWithScores(K key, final double min, final double max, final long offset, final long count) { public Set<TypedTuple<V>> reverseRangeByScoreWithScores(K key, final double min, final double max, final long offset,
final long count) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
Set<Tuple> rawValues = execute(new RedisCallback<Set<Tuple>>() { Set<Tuple> rawValues = execute(new RedisCallback<Set<Tuple>>() {
@@ -252,7 +244,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
return deserializeTupleValues(rawValues); return deserializeTupleValues(rawValues);
} }
public Long rank(K key, Object o) { public Long rank(K key, Object o) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(o); final byte[] rawValue = rawValue(o);
@@ -266,7 +257,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
}, true); }, true);
} }
public Long reverseRank(K key, Object o) { public Long reverseRank(K key, Object o) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(o); final byte[] rawValue = rawValue(o);
@@ -280,7 +270,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
}, true); }, true);
} }
public Long remove(K key, Object... values) { public Long remove(K key, Object... values) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[][] rawValues = rawValues(values); final byte[][] rawValues = rawValues(values);
@@ -293,7 +282,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
}, true); }, true);
} }
public Long removeRange(K key, final long start, final long end) { public Long removeRange(K key, final long start, final long end) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
@@ -304,7 +292,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
}, true); }, true);
} }
public Long removeRangeByScore(K key, final double min, final double max) { public Long removeRangeByScore(K key, final double min, final double max) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
return execute(new RedisCallback<Long>() { return execute(new RedisCallback<Long>() {
@@ -315,7 +302,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
}, true); }, true);
} }
public Double score(K key, Object o) { public Double score(K key, Object o) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
final byte[] rawValue = rawValue(o); final byte[] rawValue = rawValue(o);
@@ -328,7 +314,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
}, true); }, true);
} }
public Long count(K key, final double min, final double max) { public Long count(K key, final double min, final double max) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
@@ -340,7 +325,6 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
}, true); }, true);
} }
public Long size(K key) { public Long size(K key) {
final byte[] rawKey = rawKey(key); final byte[] rawKey = rawKey(key);
@@ -352,12 +336,10 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
}, true); }, true);
} }
public Long unionAndStore(K key, K otherKey, K destKey) { public Long unionAndStore(K key, K otherKey, K destKey) {
return unionAndStore(key, Collections.singleton(otherKey), destKey); return unionAndStore(key, Collections.singleton(otherKey), destKey);
} }
public Long unionAndStore(K key, Collection<K> otherKeys, K destKey) { public Long unionAndStore(K key, Collection<K> otherKeys, K destKey) {
final byte[][] rawKeys = rawKeys(key, otherKeys); final byte[][] rawKeys = rawKeys(key, otherKeys);
final byte[] rawDestKey = rawKey(destKey); final byte[] rawDestKey = rawKey(destKey);
@@ -368,4 +350,4 @@ class DefaultZSetOperations<K, V> extends AbstractOperations<K, V> implements ZS
} }
}, true); }, true);
} }
} }

View File

@@ -18,21 +18,17 @@ package org.springframework.data.redis.core;
import java.beans.PropertyEditorSupport; import java.beans.PropertyEditorSupport;
/** /**
* PropertyEditor allowing for easy injection of {@link HashOperations} from * PropertyEditor allowing for easy injection of {@link HashOperations} from {@link RedisOperations}.
* {@link RedisOperations}.
* *
* @author Costin Leau * @author Costin Leau
*/ */
class HashOperationsEditor extends PropertyEditorSupport { class HashOperationsEditor extends PropertyEditorSupport {
public void setValue(Object value) { public void setValue(Object value) {
if (value instanceof RedisOperations) { if (value instanceof RedisOperations) {
super.setValue(((RedisOperations) value).opsForHash()); super.setValue(((RedisOperations) value).opsForHash());
} } else {
else { throw new java.lang.IllegalArgumentException("Editor supports only conversion of type " + RedisOperations.class);
throw new java.lang.IllegalArgumentException("Editor supports only conversion of type "
+ RedisOperations.class);
} }
} }
} }

View File

@@ -18,20 +18,17 @@ package org.springframework.data.redis.core;
import java.beans.PropertyEditorSupport; import java.beans.PropertyEditorSupport;
/** /**
* PropertyEditor allowing for easy injection of {@link ListOperations} from * PropertyEditor allowing for easy injection of {@link ListOperations} from {@link RedisOperations}.
* {@link RedisOperations}.
* *
* @author Costin Leau * @author Costin Leau
*/ */
class ListOperationsEditor extends PropertyEditorSupport { class ListOperationsEditor extends PropertyEditorSupport {
public void setValue(Object value) { public void setValue(Object value) {
if (value instanceof RedisOperations) { if (value instanceof RedisOperations) {
super.setValue(((RedisOperations) value).opsForList()); super.setValue(((RedisOperations) value).opsForList());
} } else {
else { throw new java.lang.IllegalArgumentException("Editor supports only conversion of type " + RedisOperations.class);
throw new java.lang.IllegalArgumentException("Editor supports only conversion of type "
+ RedisOperations.class);
} }
} }
} }

View File

@@ -22,8 +22,7 @@ import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
* Base class for {@link RedisTemplate} defining common properties. * Base class for {@link RedisTemplate} defining common properties. Not intended to be used directly.
* Not intended to be used directly.
* *
* @author Costin Leau * @author Costin Leau
*/ */
@@ -40,7 +39,7 @@ public class RedisAccessor implements InitializingBean {
/** /**
* Returns the connectionFactory. * Returns the connectionFactory.
* *
* @return Returns the connectionFactory * @return Returns the connectionFactory
*/ */
public RedisConnectionFactory getConnectionFactory() { public RedisConnectionFactory getConnectionFactory() {
@@ -55,4 +54,4 @@ public class RedisAccessor implements InitializingBean {
public void setConnectionFactory(RedisConnectionFactory connectionFactory) { public void setConnectionFactory(RedisConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory; this.connectionFactory = connectionFactory;
} }
} }

View File

@@ -19,16 +19,16 @@ import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnection;
/** /**
* Callback interface for Redis 'low level' code. * Callback interface for Redis 'low level' code. To be used with {@link RedisTemplate} execution methods, often as
* To be used with {@link RedisTemplate} execution methods, often as anonymous classes within a method implementation. * anonymous classes within a method implementation. Usually, used for chaining several operations together (
* Usually, used for chaining several operations together ({@code get/set/trim etc...}. * {@code get/set/trim etc...}.
* *
* @author Costin Leau * @author Costin Leau
*/ */
public interface RedisCallback<T> { public interface RedisCallback<T> {
/** /**
* Gets called by {@link RedisTemplate} with an active Redis connection. Does not need to care about activating or * Gets called by {@link RedisTemplate} with an active Redis connection. Does not need to care about activating or
* closing the connection or handling exceptions. * closing the connection or handling exceptions.
* *
* @param connection active Redis connection * @param connection active Redis connection

View File

@@ -24,7 +24,8 @@ import org.springframework.transaction.support.TransactionSynchronizationManager
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
* Helper class featuring {@link RedisConnection} handling, allowing for reuse of instances within 'transactions'/scopes. * Helper class featuring {@link RedisConnection} handling, allowing for reuse of instances within
* 'transactions'/scopes.
* *
* @author Costin Leau * @author Costin Leau
*/ */
@@ -33,7 +34,7 @@ public abstract class RedisConnectionUtils {
private static final Log log = LogFactory.getLog(RedisConnectionUtils.class); private static final Log log = LogFactory.getLog(RedisConnectionUtils.class);
/** /**
* Binds a new Redis connection (from the given factory) to the current thread, if none is already bound. * Binds a new Redis connection (from the given factory) to the current thread, if none is already bound.
* *
* @param factory connection factory * @param factory connection factory
* @return a new Redis connection * @return a new Redis connection
@@ -43,8 +44,9 @@ public abstract class RedisConnectionUtils {
} }
/** /**
* Gets a Redis connection from the given factory. Is aware of and will return any existing corresponding connections bound to the current thread, * Gets a Redis connection from the given factory. Is aware of and will return any existing corresponding connections
* for example when using a transaction manager. Will always create a new connection otherwise. * bound to the current thread, for example when using a transaction manager. Will always create a new connection
* otherwise.
* *
* @param factory connection factory for creating the connection * @param factory connection factory for creating the connection
* @return an active Redis connection * @return an active Redis connection
@@ -54,11 +56,13 @@ public abstract class RedisConnectionUtils {
} }
/** /**
* Gets a Redis connection. Is aware of and will return any existing corresponding connections bound to the current thread, * Gets a Redis connection. Is aware of and will return any existing corresponding connections bound to the current
* for example when using a transaction manager. Will create a new Connection otherwise, if {@code allowCreate} is <tt>true</tt>. * thread, for example when using a transaction manager. Will create a new Connection otherwise, if
* {@code allowCreate} is <tt>true</tt>.
* *
* @param factory connection factory for creating the connection * @param factory connection factory for creating the connection
* @param allowCreate whether a new (unbound) connection should be created when no connection can be found for the current thread * @param allowCreate whether a new (unbound) connection should be created when no connection can be found for the
* current thread
* @param bind binds the connection to the thread, in case one was created * @param bind binds the connection to the thread, in case one was created
* @return an active Redis connection * @return an active Redis connection
*/ */
@@ -66,7 +70,7 @@ public abstract class RedisConnectionUtils {
Assert.notNull(factory, "No RedisConnectionFactory specified"); Assert.notNull(factory, "No RedisConnectionFactory specified");
RedisConnectionHolder connHolder = (RedisConnectionHolder) TransactionSynchronizationManager.getResource(factory); RedisConnectionHolder connHolder = (RedisConnectionHolder) TransactionSynchronizationManager.getResource(factory);
//TODO: investigate tx synchronization // TODO: investigate tx synchronization
if (connHolder != null) if (connHolder != null)
return connHolder.getConnection(); return connHolder.getConnection();
@@ -89,7 +93,8 @@ public abstract class RedisConnectionUtils {
} }
/** /**
* Closes the given connection, created via the given factory if not managed externally (i.e. not bound to the thread). * Closes the given connection, created via the given factory if not managed externally (i.e. not bound to the
* thread).
* *
* @param conn the Redis connection to close * @param conn the Redis connection to close
* @param factory the Redis factory that the connection was created with * @param factory the Redis factory that the connection was created with
@@ -113,7 +118,8 @@ public abstract class RedisConnectionUtils {
* @param factory Redis factory * @param factory Redis factory
*/ */
public static void unbindConnection(RedisConnectionFactory factory) { public static void unbindConnection(RedisConnectionFactory factory) {
RedisConnectionHolder connHolder = (RedisConnectionHolder) TransactionSynchronizationManager.unbindResourceIfPossible(factory); RedisConnectionHolder connHolder = (RedisConnectionHolder) TransactionSynchronizationManager
.unbindResourceIfPossible(factory);
if (connHolder != null) { if (connHolder != null) {
RedisConnection connection = connHolder.getConnection(); RedisConnection connection = connHolder.getConnection();
connection.close(); connection.close();
@@ -121,7 +127,8 @@ public abstract class RedisConnectionUtils {
} }
/** /**
* Return whether the given Redis connection is transactional, that is, bound to the current thread by Spring's transaction facilities. * Return whether the given Redis connection is transactional, that is, bound to the current thread by Spring's
* transaction facilities.
* *
* @param conn Redis connection to check * @param conn Redis connection to check
* @param connFactory Redis connection factory that the connection was created with * @param connFactory Redis connection factory that the connection was created with
@@ -131,7 +138,8 @@ public abstract class RedisConnectionUtils {
if (connFactory == null) { if (connFactory == null) {
return false; return false;
} }
RedisConnectionHolder connHolder = (RedisConnectionHolder) TransactionSynchronizationManager.getResource(connFactory); RedisConnectionHolder connHolder = (RedisConnectionHolder) TransactionSynchronizationManager
.getResource(connFactory);
return (connHolder != null && conn == connHolder.getConnection()); return (connHolder != null && conn == connHolder.getConnection());
} }
@@ -144,7 +152,6 @@ public abstract class RedisConnectionUtils {
this.conn = conn; this.conn = conn;
} }
public boolean isVoid() { public boolean isVoid() {
return isVoid; return isVoid;
} }
@@ -153,14 +160,12 @@ public abstract class RedisConnectionUtils {
return conn; return conn;
} }
public void reset() { public void reset() {
// no-op // no-op
} }
public void unbound() { public void unbound() {
this.isVoid = true; this.isVoid = true;
} }
} }
} }

View File

@@ -26,25 +26,22 @@ import org.springframework.data.redis.core.query.SortQuery;
import org.springframework.data.redis.core.script.RedisScript; import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer;
/** /**
* Interface that specified a basic set of Redis operations, implemented by {@link RedisTemplate}. * Interface that specified a basic set of Redis operations, implemented by {@link RedisTemplate}. Not often used but a
* Not often used but a useful option for extensibility and testability (as it can be easily mocked or stubbed). * useful option for extensibility and testability (as it can be easily mocked or stubbed).
* *
* @author Costin Leau * @author Costin Leau
*/ */
public interface RedisOperations<K, V> { public interface RedisOperations<K, V> {
/** /**
* Executes the given action within a Redis connection. * Executes the given action within a Redis connection. Application exceptions thrown by the action object get
* * propagated to the caller (can only be unchecked) whenever possible. Redis exceptions are transformed into
* Application exceptions thrown by the action object get propagated to the caller (can only be unchecked) whenever possible. * appropriate DAO ones. Allows for returning a result object, that is a domain object or a collection of domain
* Redis exceptions are transformed into appropriate DAO ones. * objects. Performs automatic serialization/deserialization for the given objects to and from binary data suitable
* Allows for returning a result object, that is a domain object or a collection of domain objects. * for the Redis storage. Note: Callback code is not supposed to handle transactions itself! Use an appropriate
* Performs automatic serialization/deserialization for the given objects to and from binary data suitable for the Redis storage. * transaction manager. Generally, callback code must not touch any Connection lifecycle methods, like close, to let
* * the template do its work.
* Note: Callback code is not supposed to handle transactions itself! Use an appropriate transaction manager.
* Generally, callback code must not touch any Connection lifecycle methods, like close, to let the template do its work.
* *
* @param <T> return type * @param <T> return type
* @param action callback object that specifies the Redis action * @param action callback object that specifies the Redis action
@@ -52,13 +49,10 @@ public interface RedisOperations<K, V> {
*/ */
<T> T execute(RedisCallback<T> action); <T> T execute(RedisCallback<T> action);
/** /**
* Executes a Redis session. * Executes a Redis session. Allows multiple operations to be executed in the same session enabling 'transactional'
* capabilities through {@link #multi()} and {@link #watch(Collection)} operations.
* *
* Allows multiple operations to be executed in the same session enabling 'transactional' capabilities through {@link #multi()}
* and {@link #watch(Collection)} operations.
*
* @param <T> return type * @param <T> return type
* @param session session callback * @param session session callback
* @return result object returned by the action or <tt>null</tt> * @return result object returned by the action or <tt>null</tt>
@@ -66,30 +60,30 @@ public interface RedisOperations<K, V> {
<T> T execute(SessionCallback<T> session); <T> T execute(SessionCallback<T> session);
/** /**
* Executes the given action object on a pipelined connection, returning the results. Note that the callback <b>cannot</b> * Executes the given action object on a pipelined connection, returning the results. Note that the callback
* return a non-null value as it gets overwritten by the pipeline. * <b>cannot</b> return a non-null value as it gets overwritten by the pipeline. This method will use the default
* * serializers to deserialize results
* This method will use the default serializers to deserialize results *
* * @param action callback object to execute
* @param action callback object to execute * @return list of objects returned by the pipeline
* @return list of objects returned by the pipeline */
*/
List<Object> executePipelined(RedisCallback<?> action); List<Object> executePipelined(RedisCallback<?> action);
/** /**
* Executes the given action object on a pipelined connection, returning the results using a dedicated serializer. * Executes the given action object on a pipelined connection, returning the results using a dedicated serializer.
* Note that the callback <b>cannot</b> return a non-null value as it gets overwritten by the pipeline. * Note that the callback <b>cannot</b> return a non-null value as it gets overwritten by the pipeline.
* *
* @param action callback object to execute * @param action callback object to execute
* @param resultSerializer The Serializer to use for individual values or Collections of values. If any * @param resultSerializer The Serializer to use for individual values or Collections of values. If any returned
* returned values are hashes, this serializer will be used to deserialize both the key and value * values are hashes, this serializer will be used to deserialize both the key and value
* @return list of objects returned by the pipeline * @return list of objects returned by the pipeline
*/ */
List<Object> executePipelined(final RedisCallback<?> action, final RedisSerializer<?> resultSerializer); List<Object> executePipelined(final RedisCallback<?> action, final RedisSerializer<?> resultSerializer);
/** /**
* Executes the given Redis session on a pipelined connection. Allows transactions to be pipelined. * Executes the given Redis session on a pipelined connection. Allows transactions to be pipelined. Note that the
* Note that the callback <b>cannot</b> return a non-null value as it gets overwritten by the pipeline. * callback <b>cannot</b> return a non-null value as it gets overwritten by the pipeline.
*
* @param session Session callback * @param session Session callback
* @return list of objects returned by the pipeline * @return list of objects returned by the pipeline
*/ */
@@ -97,8 +91,9 @@ public interface RedisOperations<K, V> {
/** /**
* Executes the given Redis session on a pipelined connection, returning the results using a dedicated serializer. * Executes the given Redis session on a pipelined connection, returning the results using a dedicated serializer.
* Allows transactions to be pipelined. * Allows transactions to be pipelined. Note that the callback <b>cannot</b> return a non-null value as it gets
* Note that the callback <b>cannot</b> return a non-null value as it gets overwritten by the pipeline. * overwritten by the pipeline.
*
* @param session Session callback * @param session Session callback
* @param resultSerializer * @param resultSerializer
* @return list of objects returned by the pipeline * @return list of objects returned by the pipeline
@@ -107,34 +102,26 @@ public interface RedisOperations<K, V> {
/** /**
* Executes the given {@link RedisScript} * Executes the given {@link RedisScript}
* *
* @param script * @param script The script to execute
* The script to execute * @param keys Any keys that need to be passed to the script
* @param keys * @param args Any args that need to be passed to the script
* Any keys that need to be passed to the script * @return The return value of the script or null if {@link RedisScript#getResultType()} is null, likely indicating a
* @param args * throw-away status reply (i.e. "OK")
* Any args that need to be passed to the script
* @return The return value of the script or null if {@link RedisScript#getResultType()} is
* null, likely indicating a throw-away status reply (i.e. "OK")
*/ */
<T> T execute(RedisScript<T> script, List<K> keys, Object... args); <T> T execute(RedisScript<T> script, List<K> keys, Object... args);
/** /**
* Executes the given {@link RedisScript}, using the provided {@link RedisSerializer}s to * Executes the given {@link RedisScript}, using the provided {@link RedisSerializer}s to serialize the script
* serialize the script arguments and result. * arguments and result.
* *
* @param script * @param script The script to execute
* The script to execute * @param argsSerializer The {@link RedisSerializer} to use for serializing args
* @param argsSerializer * @param resultSerializer The {@link RedisSerializer} to use for serializing the script return value
* The {@link RedisSerializer} to use for serializing args * @param keys Any keys that need to be passed to the script
* @param resultSerializer * @param args Any args that need to be passed to the script
* The {@link RedisSerializer} to use for serializing the script return value * @return The return value of the script or null if {@link RedisScript#getResultType()} is null, likely indicating a
* @param keys * throw-away status reply (i.e. "OK")
* Any keys that need to be passed to the script
* @param args
* Any args that need to be passed to the script
* @return The return value of the script or null if {@link RedisScript#getResultType()} is
* null, likely indicating a throw-away status reply (i.e. "OK")
*/ */
<T> T execute(RedisScript<T> script, RedisSerializer<?> argsSerializer, RedisSerializer<T> resultSerializer, <T> T execute(RedisScript<T> script, RedisSerializer<?> argsSerializer, RedisSerializer<T> resultSerializer,
List<K> keys, Object... args); List<K> keys, Object... args);
@@ -177,8 +164,8 @@ public interface RedisOperations<K, V> {
void unwatch(); void unwatch();
/**' /**
* * '
*/ */
void multi(); void multi();
@@ -187,14 +174,12 @@ public interface RedisOperations<K, V> {
List<Object> exec(); List<Object> exec();
/** /**
* Execute a transaction, using the provided {@link RedisSerializer} to deserialize * Execute a transaction, using the provided {@link RedisSerializer} to deserialize any results that are byte[]s or
* any results that are byte[]s or Collections of byte[]s. If a result is a Map, the * Collections of byte[]s. If a result is a Map, the provided {@link RedisSerializer} will be used for both the keys
* provided {@link RedisSerializer} will be used for both the keys and values. Other result * and values. Other result types (Long, Boolean, etc) are left as-is in the converted results. Tuple results are
* types (Long, Boolean, etc) are left as-is in the converted results. Tuple results are
* automatically converted to TypedTuples. * automatically converted to TypedTuples.
* *
* @param valueSerializer The {@link RedisSerializer} to use for deserializing the results * @param valueSerializer The {@link RedisSerializer} to use for deserializing the results of transaction exec
* of transaction exec
* @return The deserialized results of transaction exec * @return The deserialized results of transaction exec
*/ */
List<Object> exec(RedisSerializer<?> valueSerializer); List<Object> exec(RedisSerializer<?> valueSerializer);
@@ -202,7 +187,6 @@ public interface RedisOperations<K, V> {
// pubsub functionality on the template // pubsub functionality on the template
void convertAndSend(String destination, Object message); void convertAndSend(String destination, Object message);
// operation types // operation types
/** /**
* Returns the operations performed on simple values (or Strings in Redis terminology). * Returns the operations performed on simple values (or Strings in Redis terminology).
@@ -212,8 +196,7 @@ public interface RedisOperations<K, V> {
ValueOperations<K, V> opsForValue(); ValueOperations<K, V> opsForValue();
/** /**
* Returns the operations performed on simple values (or Strings in Redis terminology) * Returns the operations performed on simple values (or Strings in Redis terminology) bound to the given key.
* bound to the given key.
* *
* @param key Redis key * @param key Redis key
* @return value operations bound to the given key * @return value operations bound to the given key
@@ -222,7 +205,7 @@ public interface RedisOperations<K, V> {
/** /**
* Returns the operations performed on list values. * Returns the operations performed on list values.
* *
* @return list operations * @return list operations
*/ */
ListOperations<K, V> opsForList(); ListOperations<K, V> opsForList();
@@ -258,8 +241,7 @@ public interface RedisOperations<K, V> {
ZSetOperations<K, V> opsForZSet(); ZSetOperations<K, V> opsForZSet();
/** /**
* Returns the operations performed on zset values (also known as sorted sets) * Returns the operations performed on zset values (also known as sorted sets) bound to the given key.
* bound to the given key.
* *
* @param key Redis key * @param key Redis key
* @return zset operations bound to the given key. * @return zset operations bound to the given key.
@@ -285,7 +267,6 @@ public interface RedisOperations<K, V> {
*/ */
<HK, HV> BoundHashOperations<K, HK, HV> boundHashOps(K key); <HK, HV> BoundHashOperations<K, HK, HV> boundHashOps(K key);
List<V> sort(SortQuery<K> query); List<V> sort(SortQuery<K> query);
<T> List<T> sort(SortQuery<K> query, RedisSerializer<T> resultSerializer); <T> List<T> sort(SortQuery<K> query, RedisSerializer<T> resultSerializer);
@@ -303,4 +284,4 @@ public interface RedisOperations<K, V> {
RedisSerializer<?> getHashKeySerializer(); RedisSerializer<?> getHashKeySerializer();
RedisSerializer<?> getHashValueSerializer(); RedisSerializer<?> getHashValueSerializer();
} }

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