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

本文介绍了两种在Redis中批量获取数据的方法:使用multiGet和PipeLine。这两种方法都通过减少网络往返次数来提高效率,其中PipeLine允许在一个连接上执行多条命令。文章还提到了查询结果与键的一一对应关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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值。




### RedisTemplate 使用指南及常见问题解决 RedisTemplateSpring Data Redis 提供的核心组件之一,用于与 Redis 数据库进行交互。以下是 RedisTemplate 的使用方法以及常见问题的解决方案。 #### 1. RedisTemplate 的基本配置 在 Spring Boot 中,可以通过自定义配置类来初始化 RedisTemplate。以下是一个典型的 RedisTemplate 配置示例: ```java @Configuration @EnableCaching public class RedisConfig { @Bean public RedisConnectionFactory redisConnectionFactory() { return new JedisConnectionFactory(); // 使用 Jedis 作为 Redis 客户端 } @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); // 设置序列化方式 Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class); template.setDefaultSerializer(serializer); return template; } } ``` 上述代码中,`JedisConnectionFactory` 负责连接 Redis 服务器[^1],而 `Jackson2JsonRedisSerializer` 则用于将对象序列化为 JSON 格式存储到 Redis 中[^4]。 --- #### 2. RedisTemplate 的常用操作 RedisTemplate 提供了多种操作方法,可以对 Redis 进行键对的操作、批量操作等。以下是常用的 API 示例: - **设置键对** ```java redisTemplate.opsForValue().set("key", "value"); ``` - **获取** ```java String value = (String) redisTemplate.opsForValue().get("key"); ``` - **删除键** ```java redisTemplate.delete("key"); ``` - **设置过期时间** ```java redisTemplate.expire("key", 60, TimeUnit.SECONDS); ``` - **批量操作** ```java redisTemplate.opsForHash().putAll("hashKey", Map.of("field1", "value1", "field2", "value2")); ``` --- #### 3. 常见问题及解决方案 ##### 问题 1: `java.lang.ClassNotFoundException: redis.clients.jedis.JedisPoolConfig` 此问题通常是由于缺少 Jedis 相关依赖导致的。确保在项目的 `pom.xml` 文件中添加了正确的依赖项: ```xml <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>4.0.0</version> </dependency> ``` 此外,定期更新依赖版本以避免版本不匹配的问题[^1]。 ##### 问题 2: 缓存一致性问题 在实际开发中,缓存和数据库的一致性是一个常见的挑战。推荐先更新数据库再删除缓存的方式,以减少数据不一致的风险[^4]。 ##### 问题 3: Token 泄露风险 在使用 Redis 存储 Token 时,需要防止泄露。可以通过 Lua 脚本实现原子操作,确保 Token 的唯一性[^3]。例如: ```java String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; Long result = redisTemplate.execute( new DefaultRedisScript<>(script, Long.class), Collections.singletonList("order:token:" + token), token ); ``` --- #### 4. 最佳实践 - **定期更新依赖版本**:确保项目中的依赖保持最新,以避免版本冲突。 - **维护清晰的配置**:在使用第三方库时,始终保持清晰的配置文件和正确的实例化。 - **优先使用 Lua 脚本**:对于需要保证原子性的操作,建议使用 Lua 脚本[^3]。 --- ###
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值