Spring Boot 3集成AWS ElastiCache Redis时CONFIG命令执行异常
基于Spring Boot 3的项目,使用Redis作为数据库,通过spring-boot-starter-data-redis实现自动配置。
实体类代码
@Data @NoArgsConstructor @RedisHash public class ValidatedPhone { @Id private String phoneNumber; @Indexed private int profileId; @TimeToLive private long timeToLive; }
仓库接口代码
public interface ValidatedPhoneRepository extends CrudRepository<ValidatedPhone, String> {}
配置类代码
@Configuration @ConditionalOnProperty(prefix = "redis", name = "enabled", havingValue = "true") @EnableRedisRepositories(enableKeyspaceEvents = RedisKeyValueAdapter.EnableKeyspaceEvents.ON_STARTUP) public class RedisConfiguration { }
配置文件内容
spring: data: redis: host: ${redis.server.url} username: ${redis.server.user} password: ${redis.server.password} ssl: enabled: true
本地使用Redis 6.2时正常,但部署到AWS ElastiCache Redis时出现异常:
Caused by: io.lettuce.core.RedisCommandExecutionException: ERR unknown command
CONFIG, with args beginning with:GET,notify-keyspace-events
推测AWS Redis限制了CONFIG命令的执行,需解决该问题。
原因分析
AWS ElastiCache Redis出于安全与管理限制,禁止普通用户执行CONFIG命令。当前配置中@EnableRedisRepositories的enableKeyspaceEvents = ON_STARTUP会触发Spring Data Redis自动执行CONFIG GET/CONFIG SET来配置Redis的notify-keyspace-events参数,直接触发了AWS的限制规则。
解决方法
方法1:手动配置Redis键空间事件,关闭Spring自动配置
在AWS ElastiCache控制台配置参数
- 进入AWS ElastiCache控制台,找到目标Redis集群对应的参数组。
- 修改
notify-keyspace-events参数:若仅需TTL过期事件(适配@TimeToLive注解需求),设置为Ex;若需覆盖键创建、删除等更多事件,可设置为AKE。 - 保存参数组,若参数为静态类型,需重启Redis集群使配置生效。
修改Spring配置类
将enableKeyspaceEvents改为MANUAL,让Spring Data Redis不再尝试执行CONFIG命令,依赖Redis已配置好的事件:@Configuration @ConditionalOnProperty(prefix = "redis", name = "enabled", havingValue = "true") @EnableRedisRepositories(enableKeyspaceEvents = RedisKeyValueAdapter.EnableKeyspaceEvents.MANUAL) public class RedisConfiguration { }
方法2:关闭键空间事件(无需相关功能时)
如果项目仅依赖Redis自身的TTL过期清理,不需要Spring Data Redis的键空间事件回调逻辑,可直接关闭该功能:
@Configuration @ConditionalOnProperty(prefix = "redis", name = "enabled", havingValue = "true") @EnableRedisRepositories(enableKeyspaceEvents = RedisKeyValueAdapter.EnableKeyspaceEvents.OFF) public class RedisConfiguration { }
额外修正:配置文件缩进错误
原配置文件中spring.data.redis的缩进存在问题,会导致Redis配置不生效,修正后:
spring: data: redis: host: ${redis.server.url} username: ${redis.server.user} password: ${redis.server.password} ssl: enabled: true
内容的提问来源于stack exchange,提问作者Mr. Kadiev

