Spring RedisTemplate 批量获取值的2种方式小结

 更新时间:2022年06月07日 10:05:55   作者:Leon-Zheng  
这篇文章主要介绍了Spring RedisTemplate 批量获取值的2种方式小结,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Spring RedisTemplate 批量获取值

1、利用mGet

List<String> keys = new ArrayList<>();
//初始keys
List<YourObject> list = this.redisTemplate.opsForValue().multiGet(keys);

2、利用PipeLine

List<YourObject> list = this.redisTemplate.executePipelined(new RedisCallback<YourObject>() {
    @Override
    public YourObject doInRedis(RedisConnection connection) throws DataAccessException {
        StringRedisConnection conn = (StringRedisConnection)connection;
        for (String key : keys) {
            conn.get(key);
        }
        return null;
    }
});

其实2者底层都是用到execute方法,multiGet在使用连接是没用到pipeline,一条命令直接传给Redis,Redis返回结果。而executePipelined实际上一条或多条命令,但是共用一个连接。

    /**
     * Executes the given action object within a connection that can be exposed or not. Additionally, the connection can
     * be pipelined. Note the results of the pipeline are discarded (making it suitable for write-only scenarios).
     *
     * @param <T> return type
     * @param action callback object to execute
     * @param exposeConnection whether to enforce exposure of the native Redis Connection to callback code
     * @param pipeline whether to pipeline or not the connection for the execution
     * @return object returned by the action
     */
    public <T> T execute(RedisCallback<T> action, boolean exposeConnection, boolean pipeline) {
        Assert.isTrue(initialized, "template not initialized; call afterPropertiesSet() before using it");
        Assert.notNull(action, "Callback object must not be null");
 
        RedisConnectionFactory factory = getConnectionFactory();
        RedisConnection conn = null;
        try {
 
            if (enableTransactionSupport) {
                // only bind resources in case of potential transaction synchronization
                conn = RedisConnectionUtils.bindConnection(factory, enableTransactionSupport);
            } else {
                conn = RedisConnectionUtils.getConnection(factory);
            }
 
            boolean existingConnection = TransactionSynchronizationManager.hasResource(factory);
 
            RedisConnection connToUse = preProcessConnection(conn, existingConnection);
 
            boolean pipelineStatus = connToUse.isPipelined();
            if (pipeline && !pipelineStatus) { //开启管道
                connToUse.openPipeline();
            }
 
            RedisConnection connToExpose = (exposeConnection ? connToUse : createRedisConnectionProxy(connToUse));
            T result = action.doInRedis(connToExpose);
 
            if (pipeline && !pipelineStatus) {// 关闭管道
                connToUse.closePipeline();
            }
 
            // TODO: any other connection processing?
            return postProcessResult(result, connToUse, existingConnection);
        } finally {
 
            if (!enableTransactionSupport) {
                RedisConnectionUtils.releaseConnection(conn, factory);
            }
        }
    }

还有一点,就是查询返回的结果,和键的顺序是一一对应的,如果没查到,会返回null值。

Java对Redis的批量操作RedisTemplate

1、背景

需求:一次性获取redis缓存中多个key的value

潜在隐患:循环key,获取value,可能会造成连接池的连接数增多,连接的创建和摧毁,消耗性能

解决方法:根据项目中的缓存数据结构的实际情况,数据结构为string类型的,使用RedisTemplate的multiGet方法;数据结构为hash,使用Pipeline(管道),组合命令,批量操作redis。

2、操作

RedisTemplate的multiGet的操作

  • 针对数据结构为String类型
  • 示例代码
List<String> keys = new ArrayList<>();
for (Book e : booklist) {
   String key = generateKey.getKey(e);
   keys.add(key);
}
List<Serializable> resultStr = template.opsForValue().multiGet(keys);

此方法还是比较好用,使用者注意封装。

RedisTemplate的Pipeline使用

1)方式一 : 基础方式

  • 使用类:StringRedisTemplate
  • 使用方法
public executePipelined(RedisCallback<?> action) {...}
  • 示例代码:批量获取value
List<Object> redisResult = redisTemplate.executePipelined(new RedisCallback<String>() {
   @Override
    public String doInRedis(RedisConnection redisConnection) throws DataAccessException {  
        for (BooK e : booklist) {
       StringRedisConnection stringRedisConnection =(StringRedisConnection)redisConnection;
        stringRedisConnection.get(e.getId());
        }
       return null;
    }
});

方法二 : 使用自定义序列化方法

  • 使用类:RedisTemplate
  • 使用方法
public List<Object> executePipelined(final RedisCallback<?> action, final RedisSerializer<?> resultSerializer) {...}
  • 示例代码:批量获取hash数据结构value
List<Object> redisResult = redisTemplate.executePipelined(
  new RedisCallback<String>() {
    // 自定义序列化
    RedisSerializer keyS = redisTemplate.getKeySerializer();
    @Override
    public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
        for (BooK e : booklist) {
              redisConnection.hGet(keyS.serialize(e.getName()), keyS.serialize(e.getAuthor()));
        }
        return null;
    }
  }, redisTemplate.getValueSerializer()); // 自定义序列化

3、说明

本文简单的举了关于RedisTemplate的两个例子,但大家千万别以为只是批量取值的时候会用到,PipeLine其实是用来批量发送命令操作Redis。后来用Jedis也进行了实现,见下会分解。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • java开发微服务架构设计消息队列的水有多深

    java开发微服务架构设计消息队列的水有多深

    今天我们说说消息队列的问题,来带大家探一探消息队列的水有多深,希望看完本文大家在引入消息队列的时候先想一想,是不是一定要引入?引入消息队列后产生的问题能不能解决
    2021-10-10
  • 如何使用MyBatis Plus实现数据库curd操作

    如何使用MyBatis Plus实现数据库curd操作

    MyBatis-Plus是一个MyBatis 的增强工具,在MyBatis,的基础上只做增强不做改变,为简化开发、提高效率而生。 这篇文章主要介绍了MyBatis Plus实现数据库curd操作,需要的朋友可以参考下
    2021-09-09
  • 生成8位随机不重复的数字编号的方法

    生成8位随机不重复的数字编号的方法

    生成随机不重复的数字编号在某些情况下也会用到,本文以生成8位随机不重复的数字编号为例与大家分享下具体的实现过程,感兴趣的朋友可以参考下
    2013-09-09
  • Spring核心之IOC与bean超详细讲解

    Spring核心之IOC与bean超详细讲解

    IOC-Inversion of Control,即控制反转。它不是什么技术,而是一种设计思想。这篇文章将为大家介绍一下Spring控制反转IOC的原理,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-10-10
  • 聊聊Mybatis反射之ObjectWrapper的使用

    聊聊Mybatis反射之ObjectWrapper的使用

    本文主要介绍了Mybatis反射之ObjectWrapper的使用,文中根据实例编码详细介绍的十分详尽,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • Mybatis-Plus时间范围查询方式详解

    Mybatis-Plus时间范围查询方式详解

    这篇文章主要介绍了Mybatis-Plus时间范围查询方式详解,通过两种方式结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-09-09
  • @OneToMany查询陷入循环引用的解决方案

    @OneToMany查询陷入循环引用的解决方案

    这篇文章主要介绍了@OneToMany查询陷入循环引用的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • SpringBoot 使用 FTP 操作文件的过程(删除、上传、下载文件)

    SpringBoot 使用 FTP 操作文件的过程(删除、上传、下载文件)

    这篇文章主要介绍了SpringBoot 使用 FTP 操作文件,主要包括配置ftp服务器,上传、删除、下载文件操作,本文结合示例代码给大家介绍的非常详细,需要的朋友可以参考下
    2022-12-12
  • java动态代理详解

    java动态代理详解

    本文章要用很土的语言描述Java动态代理,力求更易被理解。Java是JDK5中新加的机制,大家都知道Spring是用Java的动态代理实现的,那这个动态代理是什么东东呢,首先他肯定是个代理,我们先讲代理,把代理弄明白了,动态代理就好说了
    2014-02-02
  • java JTree JCheckBox树复选框详解

    java JTree JCheckBox树复选框详解

    这篇文章主要为大家详细介绍了java JTree JCheckBox树复选框的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-11-11

最新评论