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也进行了实现,见下会分解。

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

相关文章

  • Spring如何使用通知 Advice 管理事务

    Spring如何使用通知 Advice 管理事务

    Spring 默认采用声明式事务管理(通过配置的方式) ,也可以实现编程式事务管理,这篇文章主要介绍了Spring使用通知Advice管理事务,需要的朋友可以参考下
    2023-06-06
  • 详解JavaWeb如何实现文件上传和下载功能

    详解JavaWeb如何实现文件上传和下载功能

    这篇文章主要介绍了如何利用JavaWeb实现文件的上传和下载功能,文中的示例代码讲解详细,对我们的学习或工作有一定的帮助,感兴趣的小伙伴可以学习一下
    2021-12-12
  • java实现文件重命名功能

    java实现文件重命名功能

    这篇文章主要介绍了java实现文件重命名功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-03-03
  • JWT概述以及Token刷新机制详解

    JWT概述以及Token刷新机制详解

    这篇文章主要介绍了JWT概述以及Token刷新机制,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-03-03
  • IDEA的Terminal无法执行git命令问题

    IDEA的Terminal无法执行git命令问题

    这篇文章主要介绍了IDEA的Terminal无法执行git命令问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09
  • Java如何实现压缩文件与解压缩zip文件

    Java如何实现压缩文件与解压缩zip文件

    这篇文章主要介绍了Java如何实现压缩文件与解压缩zip文件问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-12-12
  • 比较Java数组和各种List的性能小结

    比较Java数组和各种List的性能小结

    这篇文章主要是分别对Java数组、ArrayList、LinkedList和Vector进行随机访问和迭代等操作,并比较这种集合的性能。有需要的可以参考借鉴。
    2016-08-08
  • 基于springboot微信公众号开发(微信自动回复)

    基于springboot微信公众号开发(微信自动回复)

    这篇文章主要介绍了基于springboot微信公众号开发(微信自动回复),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-11-11
  • 深入浅析springsecurity入门登录授权

    深入浅析springsecurity入门登录授权

    SpringSecurity为我们提供了基于注解的权限控制方案,这也是我们项目中主要采用的方式,我们可以使用注解去指定访问对应的资源所需的权限,这篇文章主要介绍了springsecurity入门登录授权,需要的朋友可以参考下
    2024-05-05
  • SpringBoot连接MYSQL数据库并使用JPA进行操作

    SpringBoot连接MYSQL数据库并使用JPA进行操作

    今天给大家介绍一下如何SpringBoot中连接Mysql数据库,并使用JPA进行数据库的相关操作。
    2017-04-04

最新评论