• Springboot 中RedisTemplate使用scan来获取所有的key底层做了哪些事情


    直接上代码,围绕着代码来讨论

    redisTemplate.execute((RedisCallback<Object>) (connection) -> {
        Cursor<byte[]> scan = connection
                .scan(ScanOptions.scanOptions().count(2).match("*").build());
        scan.forEachRemaining((bytes) -> {
            System.out.println(new String(bytes));
        });
        //while (scan.hasNext()) {
        //    System.out.println(new String(scan.next()));
        //}
        return null;
    });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    通过上述代码我们可以看到,可以通过迭代器来获取到redis中单库中所有的key,但这样底层是怎么做的呢?我们现在假定有两种方案去实现这种方案。

    ① redis 客户端(jedis、lettuce)scan执行之后返回了所有的数据,迭代器next()每次都从数据集中取出一条消费。但这样有个疑点 => ScanOptions.scanOptions().count(2).match("*").build() 我们知道count(2)代表着每次只向redis中请求2条返回数据呀。如果全部返回也不符合scan命令的设计!

    ② 每次迭代next()都要判断是否数据集中还有数据,没有的话去redis中通过游标取下次一的数据集(2条)。然后将获取到数据集迭代器替换到游标中,上一个数据集回收(防止内存过大),使迭代器可以正常流转。

    在这里插入图片描述
    那上面两条都是我自己的猜测,可能两条都不对,也有可能两条对一条,具体我们还是要看源码怎么做的。

    分析源码

    Cursor scan = connection.scan(ScanOptions.scanOptions().count(2).match("*").build()); 这段代码返回了一个Cursor 游标,我们看看他的具体实现是这个类:org.springframework.data.redis.core.ScanCursor
    这个类实现了Cursor,实现了迭代器的所有方法。

    当我们执行forEachRemaining或者hasNext()的时候都会去判断

    @Override
    public boolean hasNext() {
    
    	assertCursorIsOpen();
    
    	// delegate可以理解为数据集的迭代器,是一个list类型,从redis获取到的数据集会放到这个list中
    	while (!delegate.hasNext() && !CursorState.FINISHED.equals(state)) {
    		// 可以看到如果说数据集读取完了,会继续去往redis中取下一组
    		scan(cursorId);
    	}
    
    	if (delegate.hasNext()) {
    		return true;
    	}
    
    	return cursorId > 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    scan 方法

    private void scan(long cursorId) {
    	// 去请求redis获取下一组key
    	ScanIteration<T> result = doScan(cursorId, this.scanOptions);
    	// 将数据集
    	processScanResult(result);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    processScanResult 方法

    private void processScanResult(ScanIteration<T> result) {
    
    	// redis 中的游标
    	cursorId = result.getCursorId();
    
    	if (isFinished(cursorId)) {
    		state = CursorState.FINISHED;
    	}
    
    	if (!CollectionUtils.isEmpty(result.getItems())) {
    		// 替换迭代器 *** 重要代码
    		delegate = result.iterator();
    	} else {
    		resetDelegate();
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    在这里插入图片描述
    可以看到forEachRemaining其实也要去先判断数据集中有值。

    自此我们验证了上述的两条推断中第二条是争取的,每次迭代器流转的时候都会去判断是否还有数据,没有的话就会从redis取到新的数据集,然后把数据集的迭代器替换到游标中,从而实现了redis单库取出所有的key。spring-data-redis中实现的很优雅,很巧妙,我们也可以学习这种设计模式来批量获取远程分页数据等。最后我们来看下ScanCursor的整体代码:

    /*
     * Copyright 2014-2022 the original author or authors.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      https://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    package org.springframework.data.redis.core;
    
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.NoSuchElementException;
    
    import org.springframework.dao.InvalidDataAccessApiUsageException;
    import org.springframework.lang.Nullable;
    import org.springframework.util.Assert;
    import org.springframework.util.CollectionUtils;
    
    /**
     * Redis client agnostic {@link Cursor} implementation continuously loading additional results from Redis server until
     * reaching its starting point {@code zero}. 
    * Note: Please note that the {@link ScanCursor} has to be initialized ({@link #open()} prior to usage. * * @author Christoph Strobl * @author Thomas Darimont * @author Duobiao Ou * @author Marl Paluch * @param * @since 1.4 */
    public abstract class ScanCursor<T> implements Cursor<T> { private CursorState state; // 游标状态 private long cursorId; // 游标当前位置 private Iterator<T> delegate; // 从redis获取到的结果集的迭代器,只要实现过Iterator的类都可以被代理 private final ScanOptions scanOptions; // 配置信息 private long position; // 位置 /** * Crates new {@link ScanCursor} with {@code id=0} and {@link ScanOptions#NONE} */ public ScanCursor() { this(ScanOptions.NONE); } /** * Crates new {@link ScanCursor} with {@code id=0}. * * @param options the scan options to apply. */ public ScanCursor(ScanOptions options) { this(0, options); } /** * Crates new {@link ScanCursor} with {@link ScanOptions#NONE} * * @param cursorId the cursor Id. */ public ScanCursor(long cursorId) { this(cursorId, ScanOptions.NONE); } /** * Crates new {@link ScanCursor} * * @param cursorId the cursor Id. * @param options Defaulted to {@link ScanOptions#NONE} if {@code null}. */ public ScanCursor(long cursorId, @Nullable ScanOptions options) { this.scanOptions = options != null ? options : ScanOptions.NONE; this.cursorId = cursorId; this.state = CursorState.READY; this.delegate = Collections.emptyIterator(); } private void scan(long cursorId) { ScanIteration<T> result = doScan(cursorId, this.scanOptions); processScanResult(result); } /** * Performs the actual scan command using the native client implementation. The given {@literal options} are never * {@code null}. * * @param cursorId * @param options * @return */ protected abstract ScanIteration<T> doScan(long cursorId, ScanOptions options); /** * Initialize the {@link Cursor} prior to usage. */ public final ScanCursor<T> open() { if (!isReady()) { throw new InvalidDataAccessApiUsageException("Cursor already " + state + ". Cannot (re)open it."); } state = CursorState.OPEN; doOpen(cursorId); return this; } /** * Customization hook when calling {@link #open()}. * * @param cursorId */ protected void doOpen(long cursorId) { scan(cursorId); } private void processScanResult(ScanIteration<T> result) { cursorId = result.getCursorId(); if (isFinished(cursorId)) { state = CursorState.FINISHED; } if (!CollectionUtils.isEmpty(result.getItems())) { delegate = result.iterator(); } else { resetDelegate(); } } /** * Check whether {@code cursorId} is finished. * * @param cursorId the cursor Id * @return {@literal true} if the cursor is considered finished, {@literal false} otherwise.s * @since 2.1 */ protected boolean isFinished(long cursorId) { return cursorId == 0; } private void resetDelegate() { delegate = Collections.emptyIterator(); } /* * (non-Javadoc) * @see org.springframework.data.redis.core.Cursor#getCursorId() */ @Override public long getCursorId() { return cursorId; } /* * (non-Javadoc) * @see java.util.Iterator#hasNext() */ @Override public boolean hasNext() { assertCursorIsOpen(); while (!delegate.hasNext() && !CursorState.FINISHED.equals(state)) { scan(cursorId); } if (delegate.hasNext()) { return true; } return cursorId > 0; } private void assertCursorIsOpen() { if (isReady() || isClosed()) { throw new InvalidDataAccessApiUsageException("Cannot access closed cursor. Did you forget to call open()?"); } } /* * (non-Javadoc) * @see java.util.Iterator#next() */ @Override public T next() { assertCursorIsOpen(); if (!hasNext()) { throw new NoSuchElementException("No more elements available for cursor " + cursorId + "."); } T next = moveNext(delegate); position++; return next; } /** * Fetch the next item from the underlying {@link Iterable}. * * @param source * @return */ protected T moveNext(Iterator<T> source) { return source.next(); } /* * (non-Javadoc) * @see java.util.Iterator#remove() */ @Override public void remove() { throw new UnsupportedOperationException("Remove is not supported"); } /* * (non-Javadoc) * @see java.io.Closeable#close() */ @Override public final void close() { try { doClose(); } finally { state = CursorState.CLOSED; } } /** * Customization hook for cleaning up resources on when calling {@link #close()}. */ protected void doClose() {} /* * (non-Javadoc) * @see org.springframework.data.redis.core.Cursor#isClosed() */ @Override public boolean isClosed() { return state == CursorState.CLOSED; } protected final boolean isReady() { return state == CursorState.READY; } protected final boolean isOpen() { return state == CursorState.OPEN; } /* * (non-Javadoc) * @see org.springframework.data.redis.core.Cursor#getPosition() */ @Override public long getPosition() { return position; } /** * @author Thomas Darimont */ enum CursorState { READY, OPEN, FINISHED, CLOSED; } }
    • 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
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
  • 相关阅读:
    NOIP 模拟赛 长寿花 题解
    R数据分析:用R建立预测模型
    详解4种类型的爬虫技术
    sql基础语法
    numpy 和 tensorflow 中的各种乘法(点乘和矩阵乘)
    java计算机毕业设计基于node.js的疫情大数据展示与政策查询系统
    element-plus文档地址,防止官网打不开
    浅谈人工智能视频分析技术的原理及行业场景应用
    【python】读取.dat格式文件
    “数字+”就业生态系统演进变迁机理研探
  • 原文地址:https://blog.csdn.net/yh4494/article/details/138157528