在服务器强制停止的情况下,如何防止 redis 丢失数据,从而导致 RedisCommandInterruptedException

问题描述

@Autowired
    private StringRedistemplate stringRedistemplate; 

public List<Object> getDataFromredis(String redisKey) {
        
            try {
                
                long numberOfEntriesToRead = 60000;
                return stringRedistemplate.executePipelined(
                        (RedisConnection connection) -> {
                            StringRedisConnection stringRedisConn =(StringRedisConnection)connection;
                            for (int index = 0; index < numberOfEntriesToRead; index++) {
                                stringRedisConn.lPop(redisKey);
                            }
                            return null;
                        });
            }catch (RedisCommandInterruptedException e) {
                LOGGER.error("Interrupted EXCEPTION :::",e);
            }
        } 
    }

我有一个方法可以读取给定密钥的 redis 内容。现在的问题是,当我的应用程序服务器停止而此方法试图从 redis 获取数据时,我收到 RedisCommandInterruptedException 异常,导致从 redis 丢失一些数据。那么我该如何克服这个问题任何建议都是可观的。

解决方法

管道不是原子操作,因此无法保证在发生异常时执行所有/全部命令。

您可以使用 lua 脚本或 multi command 在单个事务中进行运行操作。 您可以在此 SO thread 和此 site 中阅读有关在 Spring Boot Data redis 中使用 multi 的更多信息。