2828import org .springframework .cache .support .SimpleValueWrapper ;
2929import org .springframework .dao .DataAccessException ;
3030import org .springframework .data .redis .RedisSystemException ;
31+ import org .springframework .data .redis .connection .DecoratedRedisConnection ;
3132import org .springframework .data .redis .connection .RedisClusterConnection ;
3233import org .springframework .data .redis .connection .RedisConnection ;
3334import org .springframework .data .redis .connection .ReturnType ;
3940
4041/**
4142 * Cache implementation on top of Redis.
42- *
43+ *
4344 * @author Costin Leau
4445 * @author Christoph Strobl
4546 * @author Thomas Darimont
47+ * @author Mark Paluch
4648 */
4749@ SuppressWarnings ("unchecked" )
4850public class RedisCache implements Cache {
@@ -54,7 +56,7 @@ public class RedisCache implements Cache {
5456
5557/**
5658 * Constructs a new <code>RedisCache</code> instance.
57- *
59+ *
5860 * @param name cache name
5961 * @param prefix
6062 * @param redisOperations
@@ -624,7 +626,16 @@ public Void doInLock(RedisConnection connection) throws DataAccessException {
624626byte [] prefixToUse = Arrays .copyOf (metadata .getKeyPrefix (), metadata .getKeyPrefix ().length + WILD_CARD .length );
625627System .arraycopy (WILD_CARD , 0 , prefixToUse , metadata .getKeyPrefix ().length , WILD_CARD .length );
626628
627- connection .eval (REMOVE_KEYS_BY_PATTERN_LUA , ReturnType .INTEGER , 0 , prefixToUse );
629+ if (isClusterConnection (connection )) {
630+
631+ // load keys to the client because currently Redis Cluster connections do not allow eval of lua scripts.
632+ Set <byte []> keys = connection .keys (prefixToUse );
633+ if (!keys .isEmpty ()) {
634+ connection .del (keys .toArray (new byte [keys .size ()][]));
635+ }
636+ } else {
637+ connection .eval (REMOVE_KEYS_BY_PATTERN_LUA , ReturnType .INTEGER , 0 , prefixToUse );
638+ }
628639
629640return null ;
630641}
@@ -765,8 +776,9 @@ public byte[] doInRedis(BinaryRedisCacheElement element, RedisConnection connect
765776
766777return value ;
767778} catch (RuntimeException e ) {
768-
769- connection .discard ();
779+ if (!isClusterConnection (connection )) {
780+ connection .discard ();
781+ }
770782throw e ;
771783}
772784} finally {
@@ -810,6 +822,11 @@ public RuntimeException create(Object key, Callable<?> valueLoader, Throwable ca
810822}
811823
812824private static boolean isClusterConnection (RedisConnection connection ) {
825+
826+ while (connection instanceof DecoratedRedisConnection ) {
827+ connection = ((DecoratedRedisConnection ) connection ).getDelegate ();
828+ }
829+
813830return connection instanceof RedisClusterConnection ;
814831}
815832
0 commit comments