1268190a3bb0cf61dd33a0191794865cd75eaa82.svn-base 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. package org.jeecg.common.modules.redis.writer;
  2. import java.nio.charset.StandardCharsets;
  3. import java.time.Duration;
  4. import java.util.Collections;
  5. import java.util.Optional;
  6. import java.util.Set;
  7. import java.util.concurrent.TimeUnit;
  8. import java.util.function.Consumer;
  9. import java.util.function.Function;
  10. import lombok.extern.slf4j.Slf4j;
  11. import org.springframework.dao.PessimisticLockingFailureException;
  12. import org.springframework.data.redis.cache.RedisCacheWriter;
  13. import org.springframework.data.redis.connection.RedisConnection;
  14. import org.springframework.data.redis.connection.RedisConnectionFactory;
  15. import org.springframework.data.redis.connection.RedisStringCommands.SetOption;
  16. import org.springframework.data.redis.core.types.Expiration;
  17. import org.springframework.lang.Nullable;
  18. import org.springframework.util.Assert;
  19. /**
  20. * 该类参照 DefaultRedisCacheWriter 重写了 remove 方法实现通配符*删除
  21. */
  22. @Slf4j
  23. public class JeecgRedisCacheWriter implements RedisCacheWriter {
  24. private final RedisConnectionFactory connectionFactory;
  25. private final Duration sleepTime;
  26. public JeecgRedisCacheWriter(RedisConnectionFactory connectionFactory) {
  27. this(connectionFactory, Duration.ZERO);
  28. }
  29. public JeecgRedisCacheWriter(RedisConnectionFactory connectionFactory, Duration sleepTime) {
  30. Assert.notNull(connectionFactory, "ConnectionFactory must not be null!");
  31. Assert.notNull(sleepTime, "SleepTime must not be null!");
  32. this.connectionFactory = connectionFactory;
  33. this.sleepTime = sleepTime;
  34. }
  35. public void put(String name, byte[] key, byte[] value, @Nullable Duration ttl) {
  36. Assert.notNull(name, "Name must not be null!");
  37. Assert.notNull(key, "Key must not be null!");
  38. Assert.notNull(value, "Value must not be null!");
  39. this.execute(name, (connection) -> {
  40. if (shouldExpireWithin(ttl)) {
  41. connection.set(key, value, Expiration.from(ttl.toMillis(), TimeUnit.MILLISECONDS), SetOption.upsert());
  42. } else {
  43. connection.set(key, value);
  44. }
  45. return "OK";
  46. });
  47. }
  48. public byte[] get(String name, byte[] key) {
  49. Assert.notNull(name, "Name must not be null!");
  50. Assert.notNull(key, "Key must not be null!");
  51. return (byte[])this.execute(name, (connection) -> {
  52. return connection.get(key);
  53. });
  54. }
  55. public byte[] putIfAbsent(String name, byte[] key, byte[] value, @Nullable Duration ttl) {
  56. Assert.notNull(name, "Name must not be null!");
  57. Assert.notNull(key, "Key must not be null!");
  58. Assert.notNull(value, "Value must not be null!");
  59. return (byte[])this.execute(name, (connection) -> {
  60. if (this.isLockingCacheWriter()) {
  61. this.doLock(name, connection);
  62. }
  63. Object var7;
  64. try {
  65. boolean put;
  66. if (shouldExpireWithin(ttl)) {
  67. put = connection.set(key, value, Expiration.from(ttl), SetOption.ifAbsent());
  68. } else {
  69. put = connection.setNX(key, value);
  70. }
  71. if (!put) {
  72. byte[] var11 = connection.get(key);
  73. return var11;
  74. }
  75. var7 = null;
  76. } finally {
  77. if (this.isLockingCacheWriter()) {
  78. this.doUnlock(name, connection);
  79. }
  80. }
  81. return (byte[])var7;
  82. });
  83. }
  84. public void remove(String name, byte[] key) {
  85. Assert.notNull(name, "Name must not be null!");
  86. Assert.notNull(key, "Key must not be null!");
  87. String keyString = new String(key);
  88. log.info("redis remove key:" + keyString);
  89. if(keyString!=null && keyString.endsWith("*")){
  90. execute(name, connection -> {
  91. // 获取某个前缀所拥有的所有的键,某个前缀开头,后面肯定是*
  92. Set<byte[]> keys = connection.keys(key);
  93. int delNum = 0;
  94. for (byte[] keyByte : keys) {
  95. delNum += connection.del(keyByte);
  96. }
  97. return delNum;
  98. });
  99. }else{
  100. this.execute(name, (connection) -> {
  101. return connection.del(new byte[][]{key});
  102. });
  103. }
  104. }
  105. public void clean(String name, byte[] pattern) {
  106. Assert.notNull(name, "Name must not be null!");
  107. Assert.notNull(pattern, "Pattern must not be null!");
  108. this.execute(name, (connection) -> {
  109. boolean wasLocked = false;
  110. try {
  111. if (this.isLockingCacheWriter()) {
  112. this.doLock(name, connection);
  113. wasLocked = true;
  114. }
  115. byte[][] keys = (byte[][])((Set)Optional.ofNullable(connection.keys(pattern)).orElse(Collections.emptySet())).toArray(new byte[0][]);
  116. if (keys.length > 0) {
  117. connection.del(keys);
  118. }
  119. } finally {
  120. if (wasLocked && this.isLockingCacheWriter()) {
  121. this.doUnlock(name, connection);
  122. }
  123. }
  124. return "OK";
  125. });
  126. }
  127. void lock(String name) {
  128. this.execute(name, (connection) -> {
  129. return this.doLock(name, connection);
  130. });
  131. }
  132. void unlock(String name) {
  133. this.executeLockFree((connection) -> {
  134. this.doUnlock(name, connection);
  135. });
  136. }
  137. private Boolean doLock(String name, RedisConnection connection) {
  138. return connection.setNX(createCacheLockKey(name), new byte[0]);
  139. }
  140. private Long doUnlock(String name, RedisConnection connection) {
  141. return connection.del(new byte[][]{createCacheLockKey(name)});
  142. }
  143. boolean doCheckLock(String name, RedisConnection connection) {
  144. return connection.exists(createCacheLockKey(name));
  145. }
  146. private boolean isLockingCacheWriter() {
  147. return !this.sleepTime.isZero() && !this.sleepTime.isNegative();
  148. }
  149. private <T> T execute(String name, Function<RedisConnection, T> callback) {
  150. RedisConnection connection = this.connectionFactory.getConnection();
  151. try {
  152. this.checkAndPotentiallyWaitUntilUnlocked(name, connection);
  153. return callback.apply(connection);
  154. } finally {
  155. connection.close();
  156. }
  157. }
  158. private void executeLockFree(Consumer<RedisConnection> callback) {
  159. RedisConnection connection = this.connectionFactory.getConnection();
  160. try {
  161. callback.accept(connection);
  162. } finally {
  163. connection.close();
  164. }
  165. }
  166. private void checkAndPotentiallyWaitUntilUnlocked(String name, RedisConnection connection) {
  167. if (this.isLockingCacheWriter()) {
  168. try {
  169. while(this.doCheckLock(name, connection)) {
  170. Thread.sleep(this.sleepTime.toMillis());
  171. }
  172. } catch (InterruptedException var4) {
  173. Thread.currentThread().interrupt();
  174. throw new PessimisticLockingFailureException(String.format("Interrupted while waiting to unlock cache %s", name), var4);
  175. }
  176. }
  177. }
  178. private static boolean shouldExpireWithin(@Nullable Duration ttl) {
  179. return ttl != null && !ttl.isZero() && !ttl.isNegative();
  180. }
  181. private static byte[] createCacheLockKey(String name) {
  182. return (name + "~lock").getBytes(StandardCharsets.UTF_8);
  183. }
  184. }