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;
});

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

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

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

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

分析源码

Cursor<byte[]> 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;
}

scan 方法

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

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();
	}
}

在这里插入图片描述
可以看到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}. <br />
 * <strong>Note:</strong> 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 <T>
 * @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;
	}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/576707.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

TypeScript 中 interface 和 type 的使用#记录

一、interface&#xff1a;接口 interface A{label: string; }const aa ((aObj: A) > {console.log(aObj.label);//123return aObj.label; })aa({label: 123}) 1、可选属性 interface A{label: string;age?: number; } 2、只读属性 interface A{label: string;age?:…

【网络安全】安全事件管理处置 — windows应急响应

专栏文章索引&#xff1a;网络安全 有问题可私聊&#xff1a;QQ&#xff1a;3375119339 目录 一、账户排查 二、windows网络排查 三、进程排查 四、windows注册表排查 五、内存分析 总结 一、账户排查 账户排查主要包含以下几个维度 登录服务器的途径弱口令可疑账号 新增…

019基于JavaWeb的在线音乐系统(含论文)

019基于JavaWeb的在线音乐系统&#xff08;含论文&#xff09; 开发环境&#xff1a; Jdk7(8)Tomcat7(8)MysqlIntelliJ IDEA(Eclipse) 数据库&#xff1a; MySQL 技术&#xff1a; JavaServletJqueryJavaScriptAjaxJSPBootstrap 适用于&#xff1a; 课程设计&#xff0c;毕…

Web-SpringBootWen

创建项目 后面因为报错&#xff0c;所以我把jdk修改成22&#xff0c;仅供参考。 定义类&#xff0c;创建方法 package com.start.springbootstart.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotati…

易基因:Nat Commun:RRBS测序揭示小鼠衰老过程中的DNA甲基化变化轨迹|研究速递

大家好&#xff0c;这里是专注表观组学十余年&#xff0c;领跑多组学科研服务的易基因。 DNA甲基化数据可以生成非常精确的年龄预测器&#xff0c;但关于这一关键表观遗传生物标志物在生命周期中的动态变化知之甚少。关于衰老不连续方面的研究仍处于起步阶段&#xff0c;关键的…

冯唐成事心法笔记 —— 知人

系列文章目录 冯唐成事心法笔记 —— 知己 冯唐成事心法笔记 —— 知人 冯唐成事心法笔记 —— 知世 冯唐成事心法笔记 —— 知智慧 文章目录 系列文章目录PART 2 知人 人人都该懂战略人人都该懂战略第一&#xff0c;什么是战略第二&#xff0c;为什么要做战略第三&#xff0…

文本溢出 右侧对齐 左侧显示省略号

要想 把 “这是一段很长的文本&#xff0c;我们只想显示省略号前面的部分内容" 展示成”…只想显示省略号前面的部分内容“ 代码如下 <div class"ellipsis-start">这是一段很长的文本&#xff0c;我们只想显示省略号前面的部分内容</div>.ellips…

力扣118. 杨辉三角

Problem: 118. 杨辉三角 文章目录 题目描述思路复杂度Code 题目描述 思路 1.初始化状态&#xff1a;将创建的二维数组dp的第一列和主对角线上元素设为1&#xff1b; 2.状态的转移&#xff1a;从第一行、列起始&#xff0c;dp[i][j] dp[i - 1][j - 1] dp[i - 1][j] 复杂度 时…

vue3第二十五节(h()函数的应用)

1、前言&#xff1a; 为什么vue 中已经有 template 模板语法&#xff0c;以及JSX了&#xff0c;还要使用 h()渲染函数&#xff1b; vue 中选择默认使用template 静态模板分析&#xff0c;有利于DMO性能的提升&#xff0c;而且更接近真实的HTML&#xff0c;便于开发设计人员理…

Java之复制图片

从文件夹中复制图片 从这个文件夹&#xff1a; 复制到这个空的文件夹&#xff1a; 代码如下&#xff1a; import java.io.*; import java.util.Scanner;/*** 普通文件的复制*/public class TestDome10 {public static void main(String[] args) {// 输入两个路径// 从哪里(源路…

ssm智能停车场管理系统

视频演示效果: SSMvue智能停车场 摘 要 本论文主要论述了如何使用JAVA语言开发一个智能停车场管理系统&#xff0c;本系统将严格按照软件开发流程进行各个阶段的工作&#xff0c;采用B/S架构&#xff0c;面向对象编程思想进行项目开发。在引言中&#xff0c;作者将论述智能停车…

2024多用户商城系统哪家产品好

在当今激烈的电商竞争中&#xff0c;搭建一个功能强大、性能稳定的多用户商城系统至关重要。针对这一需求&#xff0c;以下是我为您推荐的五款优秀多用户商城系统&#xff0c;它们在功能、定制性、安全性和用户体验方面均表现出色&#xff0c;为您的电商平台搭建提供了可靠的解…

C++从入门到精通——C++动态内存管理

C动态内存管理 前言一、C/C内存分布分类1分类2题目选择题sizeof 和 strlen 区别示例sizeofstrlen 二、C语言中动态内存管理方式malloc/calloc/realloc/free示例例题malloc/calloc/realloc的区别malloc的实现原理 三、C内存管理方式new/delete操作内置类型new和delete操作自定义…

底层逻辑(1) 是非对错

底层逻辑(1) 是非对错 关于本书 这本书的副标题叫做&#xff1a;看清这个世界的底牌。让我想起电影《教父》中的一句名言&#xff1a;花半秒钟就看透事物本质的人&#xff0c;和花一辈子都看不清事物本质的人&#xff0c;注定是截然不同的命运。 如果你看过梅多丝的《系统之美…

Lagent AgentLego 智能体应用搭建-作业六

本次课程由Lagent&AgentLego 核心贡献者樊奇老师讲解【Lagent & AgentLego 智能体应用搭建】课程。分别是&#xff1a; Agent 理论及 Lagent&AgentLego 开源产品介绍Lagent 调用已有 Arxiv 论文搜索工具实战Lagent 新增自定义工具实战&#xff08;以查询天气的工具…

不对称催化(三)- 动态动力学拆分动态动力学不对称转化

一、动力学拆分的基本概念&#xff1a; 动力学拆分的最大理论产率为50%&#xff0c;通过的差异可以将两个对映异构体转化为不同构型的产物&#xff0c;通常情况下使用两个不同反应路径来实现。但是化学家们提供了一个更加实用的方法&#xff0c;通过底物的构型变化实现高于50%的…

【Leetcode】377. 组合总和 Ⅳ

文章目录 题目思路代码复杂度分析时间复杂度空间复杂度 结果总结 题目 题目链接&#x1f517; 给你一个由 不同 整数组成的数组 n u m s nums nums&#xff0c;和一个目标整数 t a r g e t target target 。请你从 n u m s nums nums 中找出并返回总和为 t a r g e t targ…

MySQL随便聊----之MySQL的调控按钮-启动选项和系统变量

-------MySQL是怎么运行的 基本介绍 如果你用过手机&#xff0c;你的手机上一定有一个设置的功能&#xff0c;你可以选择设置手机的来电铃声、设置音量大小、设置解锁密码等等。假如没有这些设置功能&#xff0c;我们的生活将置于尴尬的境地&#xff0c;比如在图书馆里无法把手…

炫云云渲染:免费体验与高性价比的首选,设计师们的渲染利器

使用云渲染是要收费的&#xff0c;如果你是第一次使用&#xff0c;是可以白嫖一波云渲染的&#xff0c;所有的云渲染都会或多或少送一些渲染券&#xff0c;你可以用它们送的渲染券免费渲一波图。但是不能一直白嫖&#xff0c;再次注册账号人家就不会送体验券了&#xff0c;有些…

茴香豆:搭建你的RAG智能助理-作业三

本次课程由书生浦语社区贡献者【北辰】老师讲解【茴香豆&#xff1a;搭建你的 RAG 智能助理】课程。分别是&#xff1a; RAG 基础介绍茴香豆产品简介使用茴香豆搭建RAG知识库实战 课程视频&#xff1a;https://www.bilibili.com/video/BV1QA4m1F7t4/ 课程文档&#xff1a;ht…
最新文章