java110
2020-10-22 17764bd12c42512189ea5c71fac8be2614fb7589
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package com.java110.core.cache;
 
import com.java110.utils.util.Assert;
import org.springframework.dao.PessimisticLockingFailureException;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.lang.Nullable;
 
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Collections;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
 
/**
 * 自定义redis 缓存器
 */
public class Java110RedisCacheWriter implements RedisCacheWriter {
 
 
    private final RedisConnectionFactory connectionFactory;
 
    private final Duration sleepTime;
 
    /**
     * @param connectionFactory must not be {@literal null}.
     */
    Java110RedisCacheWriter(RedisConnectionFactory connectionFactory) {
        this(connectionFactory, Duration.ZERO);
    }
 
    /**
     * @param connectionFactory must not be {@literal null}.
     * @param sleepTime         sleep time between lock request attempts. Must not be {@literal null}. Use {@link Duration#ZERO}
     *                          to disable locking.
     */
    Java110RedisCacheWriter(RedisConnectionFactory connectionFactory, Duration sleepTime) {
 
        Assert.notNull(connectionFactory, "ConnectionFactory must not be null!");
        Assert.notNull(sleepTime, "SleepTime must not be null!");
 
        this.connectionFactory = connectionFactory;
        this.sleepTime = sleepTime;
    }
 
    @Override
    public void put(String name, byte[] key, byte[] value, @Nullable Duration ttl) {
 
        Assert.notNull(name, "Name must not be null!");
        Assert.notNull(key, "Key must not be null!");
        if (value == null) {
            return;
        }
 
        execute(name, connection -> {
 
            //当设置了过期时间,则修改取出
            //@Cacheable(value="user-key#key_expire=1200",key = "#id",condition = "#id != 2")
            //name 对应 value
            //key 对应 value :: key
 
            //判断name里面是否设置了过期时间,如果设置了则对key进行缓存,并设置过期时间
            int index = name.lastIndexOf(Java110RedisConfig.REDIS_EXPIRE_TIME_KEY);
            if (index > 0) {
                //取出对应的时间 1200 index + 1是还有一个=号
                String expireString = name.substring(index + 1 + Java110RedisConfig.REDIS_EXPIRE_TIME_KEY.length());
                long expireTime = Long.parseLong(expireString);
                connection.set(key, value, Expiration.from(expireTime, TimeUnit.SECONDS), RedisStringCommands.SetOption.upsert());
            } else if (shouldExpireWithin(ttl)) {
                connection.set(key, value, Expiration.from(ttl.toMillis(), TimeUnit.MILLISECONDS), RedisStringCommands.SetOption.upsert());
            } else {
                connection.set(key, value);
            }
            return "OK";
        });
    }
 
    /*
     * (non-Javadoc)
     * @see org.springframework.data.redis.cache.RedisCacheWriter#get(java.lang.String, byte[])
     */
    @Override
    public byte[] get(String name, byte[] key) {
 
        org.springframework.util.Assert.notNull(name, "Name must not be null!");
        org.springframework.util.Assert.notNull(key, "Key must not be null!");
 
        return execute(name, connection -> connection.get(key));
    }
 
    /*
     * (non-Javadoc)
     * @see org.springframework.data.redis.cache.RedisCacheWriter#putIfAbsent(java.lang.String, byte[], byte[], java.time.Duration)
     */
    @Override
    public byte[] putIfAbsent(String name, byte[] key, byte[] value, @Nullable Duration ttl) {
 
        org.springframework.util.Assert.notNull(name, "Name must not be null!");
        org.springframework.util.Assert.notNull(key, "Key must not be null!");
        org.springframework.util.Assert.notNull(value, "Value must not be null!");
 
        return execute(name, connection -> {
 
            if (isLockingCacheWriter()) {
                doLock(name, connection);
            }
 
            try {
                if (connection.setNX(key, value)) {
 
                    if (shouldExpireWithin(ttl)) {
                        connection.pExpire(key, ttl.toMillis());
                    }
                    return null;
                }
 
                return connection.get(key);
            } finally {
 
                if (isLockingCacheWriter()) {
                    doUnlock(name, connection);
                }
            }
        });
    }
 
    /*
     * (non-Javadoc)
     * @see org.springframework.data.redis.cache.RedisCacheWriter#remove(java.lang.String, byte[])
     */
    @Override
    public void remove(String name, byte[] key) {
 
        org.springframework.util.Assert.notNull(name, "Name must not be null!");
        org.springframework.util.Assert.notNull(key, "Key must not be null!");
 
        execute(name, connection -> connection.del(key));
    }
 
    /*
     * (non-Javadoc)
     * @see org.springframework.data.redis.cache.RedisCacheWriter#clean(java.lang.String, byte[])
     */
    @Override
    public void clean(String name, byte[] pattern) {
 
        Assert.notNull(name, "Name must not be null!");
        Assert.notNull(pattern, "Pattern must not be null!");
 
        execute(name, connection -> {
 
            boolean wasLocked = false;
 
            try {
 
                if (isLockingCacheWriter()) {
                    doLock(name, connection);
                    wasLocked = true;
                }
 
                byte[][] keys = Optional.ofNullable(connection.keys(pattern)).orElse(Collections.emptySet())
                        .toArray(new byte[0][]);
 
                if (keys.length > 0) {
                    connection.del(keys);
                }
            } finally {
 
                if (wasLocked && isLockingCacheWriter()) {
                    doUnlock(name, connection);
                }
            }
 
            return "OK";
        });
    }
 
    /**
     * Explicitly set a write lock on a cache.
     *
     * @param name the name of the cache to lock.
     */
    void lock(String name) {
        execute(name, connection -> doLock(name, connection));
    }
 
    /**
     * Explicitly remove a write lock from a cache.
     *
     * @param name the name of the cache to unlock.
     */
    void unlock(String name) {
        executeLockFree(connection -> doUnlock(name, connection));
    }
 
    private Boolean doLock(String name, RedisConnection connection) {
        return connection.setNX(createCacheLockKey(name), new byte[0]);
    }
 
    private Long doUnlock(String name, RedisConnection connection) {
        return connection.del(createCacheLockKey(name));
    }
 
    boolean doCheckLock(String name, RedisConnection connection) {
        return connection.exists(createCacheLockKey(name));
    }
 
    /**
     * @return {@literal true} if {@link RedisCacheWriter} uses locks.
     */
    private boolean isLockingCacheWriter() {
        return !sleepTime.isZero() && !sleepTime.isNegative();
    }
 
    private <T> T execute(String name, Function<RedisConnection, T> callback) {
 
        RedisConnection connection = connectionFactory.getConnection();
        try {
 
            checkAndPotentiallyWaitUntilUnlocked(name, connection);
            return callback.apply(connection);
        } finally {
            connection.close();
        }
    }
 
    private void executeLockFree(Consumer<RedisConnection> callback) {
 
        RedisConnection connection = connectionFactory.getConnection();
 
        try {
            callback.accept(connection);
        } finally {
            connection.close();
        }
    }
 
    private void checkAndPotentiallyWaitUntilUnlocked(String name, RedisConnection connection) {
 
        if (!isLockingCacheWriter()) {
            return;
        }
 
        try {
 
            while (doCheckLock(name, connection)) {
                Thread.sleep(sleepTime.toMillis());
            }
        } catch (InterruptedException ex) {
 
            // Re-interrupt current thread, to allow other participants to react.
            Thread.currentThread().interrupt();
 
            throw new PessimisticLockingFailureException(String.format("Interrupted while waiting to unlock cache %s", name),
                    ex);
        }
    }
 
    private static boolean shouldExpireWithin(@Nullable Duration ttl) {
        return ttl != null && !ttl.isZero() && !ttl.isNegative();
    }
 
    private static byte[] createCacheLockKey(String name) {
        return (name + "~lock").getBytes(StandardCharsets.UTF_8);
    }
}