Redis使用Pipeline(管道)批量处理

Redis 批量处理

在开发中,有时需要对Redis 进行大批量的处理。

比如Redis批量查询多个Hash。如果是在for循环中逐个查询,那性能会很差。

这时,可以使用 Pipeline (管道)。

Pipeline (管道)

Pipeline (管道) 可以一次性发送多条命令并在执行完后一次性将结果返回,pipeline 通过减少客户端与 redis 的通信次数来实现降低往返延时时间,而且 Pipeline 实现的原理是队列,而队列的原理是时先进先出,这样就保证数据的顺序性。

RedisTemplate的管道操作

RedisTemplate的管道操作,使用**executePipelined()**方法。
org.springframework.data.redis.core.RedisTemplate#executePipelined(org.springframework.data.redis.core.SessionCallback<?>)

	@Overridepublic List<Object> executePipelined(SessionCallback<?> session, @Nullable RedisSerializer<?> resultSerializer) {Assert.isTrue(initialized, "template not initialized; call afterPropertiesSet() before using it");Assert.notNull(session, "Callback object must not be null");RedisConnectionFactory factory = getRequiredConnectionFactory();// 绑定连接RedisConnectionUtils.bindConnection(factory, enableTransactionSupport);try {return execute((RedisCallback<List<Object>>) connection -> {//打开管道connection.openPipeline();boolean pipelinedClosed = false;try {Object result = executeSession(session);//callback的返回值,只能返回null,否则会报错。if (result != null) {throw new InvalidDataAccessApiUsageException("Callback cannot return a non-null value as it gets overwritten by the pipeline");}//关闭管道,并获取返回值List<Object> closePipeline = connection.closePipeline();pipelinedClosed = true;return deserializeMixedResults(closePipeline, resultSerializer, hashKeySerializer, hashValueSerializer);} finally {if (!pipelinedClosed) {connection.closePipeline();}}});} finally {RedisConnectionUtils.unbindConnection(factory);}}
  • 注意:
    (1) executePipelined()的callback参数,实现execute() 方法只能返回null,否则会报错。
    报错: InvalidDataAccessApiUsageException: Callback cannot return a non-null value as it gets overwritten by the pipeline
    源码如下:
Object result = executeSession(session);
if (result != null) {
throw new InvalidDataAccessApiUsageException(
"Callback cannot return a non-null value as it gets overwritten by the pipeline");
}

(2)在executePipelined()中, 使用 get()方法 得到的value会是null。
在 redisTemplate进行管道操作,结果值只能通过 executePipelined()方法的返回值List获取.

	/*** Get the value of {@code key}.** @param key must not be {@literal null}.* 在管道(pipeline)中使用 get()方法 得到的value会是null* @return {@literal null} when used in pipeline / transaction.*/@NullableV get(Object key);
  • redisTemplate获取管道返回值:
List<Object> list = stringRedisTemplate.executePipelined(new SessionCallback<String>() {@Overridepublic  String execute(@NonNull RedisOperations operations) throws DataAccessException {//idList是多个id的集合for (String id : idList) {//key由前缀加唯一id组成String key = KEY_PREFIX + id;//在管道中使用 get()方法 得到的value会是null。value通过executePipelined()的返回值List<Object>获取。operations.opsForHash().get(key, field);}//Callback只能返回null, 否则报错:// InvalidDataAccessApiUsageException: Callback cannot return a non-null value as it gets overwritten by the pipelinereturn null;}});list.forEach(System.out::println);

Jedis操作管道

RedisTemplate操作管道比较方便,但如果要组装key和value的map,就会比较麻烦。
在这种情况下,可以使用Jedis。
比如,Jedis批量查询多个Hash,可以使用 Pipeline (管道)。
源码见: redis.clients.jedis.PipelineBase#hget(java.lang.String, java.lang.String)
hget()方法,跟普通hash的hget()有点类似,不过返回值是 Response。

    public Response<String> hget(String key, String field) {this.getClient(key).hget(key, field);return this.getResponse(BuilderFactory.STRING);}

示例:

public void testPipLine() {Map<String, Response<String>> responseMap = new HashMap<>();//try-with-resources, 自动关闭资源//先连接jedis,再拿到 pipelinetry (Jedis jedis = getJedis();Pipeline pipeline = jedis.pipelined()) {for (String id : idList) {//前缀加唯一idString key = KEY_PREFIX +  id;//使用pipeline.hget查询hash的数据Response<String> response = pipeline.hget(key, field);responseMap.put(id, response);}pipeline.sync();} catch (Exception ex) {log.error("responses error.", ex);}Map<String, String> map = new HashMap<>();//组装map。response.get()在pipeline关闭后才能执行,否则拿到的value都是nullresponseMap.forEach((k,response) -> map.put(k, response.get()));map.forEach((k,v)-> System.out.println(k+",val:"+v));}private static Pool<Jedis> jedisPool = null;/*** 连接redis,获取jedisPool* @return*/public Jedis getJedis() {if (jedisPool == null) {JedisPoolConfig poolConfig = new JedisPoolConfig();poolConfig.setMaxTotal(maxTotal);poolConfig.setMaxIdle(maxIdle);poolConfig.setMaxWaitMillis(maxWaitMillis);poolConfig.setTestOnBorrow(testOnBorrow);//配置可以写在配置中心/文件jedisPool = new JedisPool(poolConfig, host, port, timeout, password, database);}return jedisPool.getResource();}

参考资料

https://redis.io/docs/manual/pipelining/
https://www.cnblogs.com/expiator/p/11127719.html

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【操作系统】考研真题攻克与重点知识点剖析 - 第 3 篇:内存管理

前言 本文基础知识部分来自于b站&#xff1a;分享笔记的好人儿的思维导图与王道考研课程&#xff0c;感谢大佬的开源精神&#xff0c;习题来自老师划的重点以及考研真题。此前我尝试了完全使用Python或是结合大语言模型对考研真题进行数据清洗与可视化分析&#xff0c;本人技术…

Git 服务器上的 LFS 下载

以llama为例&#xff1a; https://huggingface.co/meta-llama/Llama-2-7b-hf Github # 1. 安装完成后&#xff0c;首先先初始化&#xff1b;如果有反馈&#xff0c;一般表示初始化成功 git lfs install ​ # 2. 如果刚刚下载的那个项目没啥更改&#xff0c;重新下一遍&#x…

TP触摸屏调试

此处以MT6739 1g版本敦泰TP为例(kernel 4.19),主要修改点如下: 1. 两个配置文件defconfig: kernel-4.19\arch\arm\configs\k39tv1_bsp_1g_k419_debug_defconfig: kernel-4.19\arch\arm\configs\k39tv1_bsp_1g_k419_defconfig: CONFIG_INPUT_TOUCHSCREEN=y CONFIG_TOUCHSCRE…

一文了解游戏行业(数据分析)

一.概况 1.基本术语 游戏行业基础术语——持续更新ing... 2.产业链 包括游戏开发&#xff0c;发行和销售等环节 ①游戏开发 上游环节是游戏产业链的核心环节&#xff0c;包括游戏策划&#xff0c;美术设计&#xff0c;程序开发等&#xff0c;是决定游戏质量与内容的关键因…

Leetcode刷题详解—— 有效的数独

1. 题目链接&#xff1a;36. 有效的数独 2. 题目描述&#xff1a; 请你判断一个 9 x 9 的数独是否有效。只需要 根据以下规则 &#xff0c;验证已经填入的数字是否有效即可。 数字 1-9 在每一行只能出现一次。数字 1-9 在每一列只能出现一次。数字 1-9 在每一个以粗实线分隔的…

sass 封装媒体查询工具

背景 以往写媒体查询可能是这样的&#xff1a; .header {display: flex;width: 100%; }media (width > 320px) and (width < 480px) {.header {height: 50px;} }media (width > 480px) and (width < 768px) {.header {height: 60px;} }media (width > 768px) …

解决ios向mac复制文字不成功的一种方法

### 环境&#xff1a; ios: 16.7.2 macos: 13.6.1 ### 问题现象&#xff1a; 从ios复制了文字&#xff0c;在mac上粘贴总是不成功&#xff0c;总是粘贴出mac上复制的内容。 ### 问题分析&#xff1a; 可能是mac复制的内容优先级比ios复制的内容优先级高&#xff0c;所以不清…

Python实战 | 使用 Python 和 TensorFlow 构建卷积神经网络(CNN)进行人脸识别

专栏集锦&#xff0c;大佬们可以收藏以备不时之需 Spring Cloud实战专栏&#xff1a;https://blog.csdn.net/superdangbo/category_9270827.html Python 实战专栏&#xff1a;https://blog.csdn.net/superdangbo/category_9271194.html Logback 详解专栏&#xff1a;https:/…

链表的逆置

方法1&#xff1a; 依次将指针反向&#xff0c;最后令头指针指向尾元素。 逆置过程如下&#xff1a; 当q指针为空时&#xff0c;循环结束。 //试写一算法&#xff0c;对单链表实现就地逆置&#xff0c; void Reverse1(List plist)//太复杂,不用掌握 {assert(plist ! NULL);i…

Spark Job优化

1 Map端优化 1.1 Map端聚合 map-side预聚合&#xff0c;就是在每个节点本地对相同的key进行一次聚合操作&#xff0c;类似于MapReduce中的本地combiner。map-side预聚合之后&#xff0c;每个节点本地就只会有一条相同的key&#xff0c;因为多条相同的key都被聚合起来了。其他节…

基于轻量级卷积神经网络CNN开发构建打架斗殴识别分析系统

在很多公共场合中&#xff0c;因为一些不可控因素导致最终爆发打架斗殴或者大规则冲突事件的案例层出不穷&#xff0c;基于视频监控等技术手段智能自动化地识别出已有或者潜在的危险行为对于维护公共场合的安全稳定有着重要的意义。本文的核心目的就是想要基于CNN模型来尝试开发…

Mathtype公式自动转Word自带公式

Mathtype公式自动转Word自带公式 前言/word技巧探索过程参考资料&#xff08;有效与无效&#xff09;全自动方案/代码/教程 前言/word技巧 word公式 用ALT号可以输入简单latex显示公式&#xff1b;复杂度&#xff0c;需要引入latex包的不行&#xff1b;显示不出来的话按一下en…

CentOS指令学习

目录 一、常用命令 1、ls 2、cd_pwd 3、touch_mkdir_rmdir_rm 4、cp_mv 5、whereis_which_PATH 6、find 7、grep 8、man_help 9、关机与重启 二、压缩解压 1、zip_unzip 2、gzip_gunzip 3、tar 三、其他指令 1、查看用户登录信息 2、磁盘使用情况 3、查看文件…

本地部署_语音识别工具_Whisper

1 简介 Whisper 是 OpenAI 的语音识别系统&#xff08;几乎是最先进&#xff09;&#xff0c;它是免费的开源模型&#xff0c;可供本地部署。 2 docker https://hub.docker.com/r/onerahmet/openai-whisper-asr-webservice 3 github https://github.com/ahmetoner/whisper…

74HC165 并入串出

/******************************************************** 程序名&#xff1a;main.C 版 本&#xff1a;Ver1.0 芯 片&#xff1a;AT89C51或STC89C51 晶 体&#xff1a;片外12MHz 编 程: Joey 日 期&#xff1a;2023-11-13 描 述&#xff1a;通过 74HC165 对 16 按键…

Radius是什么意思? 安当加密

Radius是什么意思&#xff1f; RADIUS&#xff08;Remote Authentication Dial In User Service&#xff09;是一种远程用户拨号认证系统&#xff0c;它由RFC 2865和RFC 2866定义&#xff0c;是应用最广泛的AAA&#xff08;Authentication、Authorization、Accounting&#xf…

Codeforces Round 788 (Div. 2) E. Hemose on the Tree(树上构造)

题目 t(t<5e4)组样例&#xff0c;每次给定一个数p&#xff0c; 表示一棵节点数为的树&#xff0c; 以下n-1条边&#xff0c;读入树边 对于n个点和n-1条边&#xff0c;每个点需要赋权&#xff0c;每条边需要赋权&#xff0c; 权值需要恰好构成[1,2n-1]的排列 并且当你赋…

MATLAB算法实战应用案例精讲-【图像处理】人脸识别

目录 前言 算法原理 什么是人脸识别? 人脸识别步骤 人脸识别技术优势及局限性

《网络协议》04. 应用层(DNS DHCP HTTP)

title: 《网络协议》04. 应用层&#xff08;DNS & DHCP & HTTP&#xff09; date: 2022-09-05 14:28:22 updated: 2023-11-12 06:55:52 categories: 学习记录&#xff1a;网络协议 excerpt: 应用层、DNS、DHCP、HTTP&#xff08;URI & URL&#xff0c;ABNF&#xf…

【数据结构初阶】顺序表SeqList

描述 顺序表我们可以把它想象成在一个表格里面填数据&#xff0c;并对数据做调整&#xff1b; 那我们的第一个问题是&#xff1a;怎么样在创建出足够的空间呢&#xff1f; 我们可以去堆上申请&#xff0c;用一个指针指向一块空间&#xff0c;如果申请的空间不够&#xff0c;我…