3.Spring Boot Redis

本文通过Spring Boot项目演示如何利用Spring框架的web、redis、jpa及thymeleaf组件来实现用户信息的获取并缓存到Redis中。具体包括Redis的安装配置、Spring Boot项目的pom文件配置、Redis配置属性的设定以及缓存管理器和模板的定制化配置。

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

[作者信息] github: https://github.com/MiniPa email: eric.fourpackcn@outlook.com

[项目代码:https://github.com/MiniPa/spring_boot_demos]

===============================================================================

   

[案例介绍]

利用spring的 web/redis/jpa/thymeleaf来实现,访问/getUser时候缓存User到redis.

Redis适合缓存,经常使用不易变动的内容。

   

[配置和使用]

1.reids安装和配置

安装Reids,我安装的实在linux上,需将redis.conf文件中的bind 127.0.0.1 改为 bind 0.0.0.0,以便能够从外部访问。

安装redis http://www.runoob.com/redis/redis-install.html

https://redis.io/download

   

1.pom: spring-session-data-redis spring-boot-starter-redis

2.redis配置

### REDIS (RedisProperties)

# Redis数据库索引(默认为0)

spring.redis.database=0

# Redis服务器地址

#spring.redis.host=192.168.1.233

spring.redis.host=192.168.245.222

# Redis服务器连接端口

spring.redis.port=6379

# Redis服务器连接密码(默认为空)

spring.redis.password=

# 连接池最大连接数(使用负值表示没有限制)

spring.redis.pool.max-active=8

# 连接池最大阻塞等待时间(使用负值表示没有限制)

spring.redis.pool.max-wait=-1

# 连接池中的最大空闲连接

spring.redis.pool.max-idle=8

# 连接池中的最小空闲连接

spring.redis.pool.min-idle=0

# 连接超时时间(毫秒)

spring.redis.timeout=0

3.cache配置

@Configuration

@EnableCaching

public class RedisConfig extends CachingConfigurerSupport {

   

@Bean

public KeyGenerator keyGenerator() {

return new KeyGenerator() {

@Override

public Object generate(Object target, Method method, Object... params) {

StringBuilder sb = new StringBuilder();

sb.append(target.getClass().getName());

sb.append(method.getName());

for (Object obj : params) {

sb.append(obj.toString());

}

return sb.toString();

}

};

}

   

@SuppressWarnings("rawtypes")

@Bean

public CacheManager cacheManager(RedisTemplate redisTemplate) {

RedisCacheManager rcm = new RedisCacheManager(redisTemplate);

//设置缓存过期时间

//rcm.setDefaultExpiration(60);//秒

return rcm;

}

   

@Bean

public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {

StringRedisTemplate template = new StringRedisTemplate(factory);

Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

   

ObjectMapper om = new ObjectMapper();

om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

jackson2JsonRedisSerializer.setObjectMapper(om);

template.setValueSerializer(jackson2JsonRedisSerializer);

template.afterPropertiesSet();

return template;

}

   

}

4.然后可以直接使用

  

   

2.Session 配置

@Configuration

@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30)

public class SessionConfig {

}

   

   

   

   

  

   

   

   

<think>我们正在处理用户的问题:如何解决Spring BootRedis配置属性绑定失败的问题,具体错误是`Failed to bind properties under &#39;spring.redis.lettuce&#39; to RedisProperties$Lettuce: ConverterNotFoundException`。 根据用户提供的引用信息,我们可以分析: 引用[1]和[2]是关于属性绑定失败的例子,其中引用[2]指出是因为类型转换失败(String转int)。引用[3]和[4]则提供了其他配置问题的解决方法。 但是,当前用户的问题是关于`spring.redis.lettuce`属性绑定到`RedisProperties$Lettuce`时出现`ConverterNotFoundException`。这意味着Spring Boot在尝试将配置文件中的属性绑定到`Lettuce`类型的属性时,找不到合适的转换器来转换某些属性值。 可能的原因: 1. 配置属性值类型不匹配:例如,配置文件中为某个属性指定了字符串,但目标属性需要的是一个复杂类型(如对象、枚举等),而Spring Boot没有内置的转换器。 2. 配置属性名不正确:可能配置了错误的属性名,导致无法绑定。 3. 依赖缺失:可能缺少必要的依赖,导致转换器不可用。 解决方案: 1. 检查配置属性:确保在`application.properties`或`application.yml`中,`spring.redis.lettuce`下的属性名称和结构正确。参考Spring Boot官方文档中关于Redis配置的部分。 2. 检查属性值类型:确保为每个属性提供的值类型与目标类型匹配。例如,如果目标是一个数值类型,不要用引号括起来(在.properties文件中,字符串不需要引号,但要注意转义)。 3. 检查依赖:确保项目中包含了必要的依赖,特别是与配置处理器和Redis相关的依赖。 具体步骤: 步骤1:检查配置 在`application.properties`中,`spring.redis.lettuce`的配置通常如下: ``` spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.min-idle=0 ``` 或者,在`application.yml`中: ```yaml spring: redis: lettuce: pool: max-active: 8 max-idle: 8 min-idle: 0 ``` 步骤2:检查属性名拼写 确保属性名完全正确,例如`max-active`而不是`maxActive`(在properties文件中,使用短横线分隔)。 步骤3:添加配置处理器依赖 在`pom.xml`中添加配置处理器依赖,它可以帮助我们在配置时获得元数据支持,从而避免一些配置错误: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> ``` 步骤4:清理和重新构建 有时,清理并重新构建项目可以解决一些配置绑定问题,因为配置处理器会生成元数据。 步骤5:检查版本兼容性 确保使用的Spring Boot版本与配置属性兼容。不同版本的Spring Boot可能对配置属性的支持有所不同。 步骤6:如果使用自定义转换器 如果上述步骤不能解决问题,并且错误信息明确提到`ConverterNotFoundException`,那么可能需要为自定义类型提供转换器。但是,`RedisProperties$Lettuce`是Spring Boot内置的类型,通常不需要自定义转换器。所以这种情况较少见。 如果问题仍然存在,可以尝试简化配置,逐步排除。 根据引用[4]中提到的类似错误,注意配置的格式和参数是否正确。 由于错误信息提到了`ConverterNotFoundException`,我们可以推测Spring Boot在绑定过程中尝试将配置值转换为某个类型,但没有找到合适的转换器。这通常发生在配置属性需要非简单类型(如枚举、自定义对象)时。 在`RedisProperties.Lettuce`类中,我们查看其属性: - `shutdownTimeout`:是`Duration`类型,Spring Boot有内置的`Duration`转换器,所以应该可以转换。但是,如果配置的字符串格式不符合,可能会导致转换失败。 - `pool`:是`Pool`类型,它内部有`maxActive`、`maxIdle`等整数属性,这些应该没有问题。 因此,问题可能出现在`shutdownTimeout`的配置上。例如,配置`spring.redis.lettuce.shutdown-timeout=100`,这里100会被转换为100毫秒。但是,如果配置了一个无法解析为`Duration`的字符串,就会导致转换失败。 所以,检查`spring.redis.lettuce.shutdown-timeout`的配置值,确保它是一个有效的持续时间表达式,如`10s`、`1m`等。 示例配置: ``` spring.redis.lettuce.shutdown-timeout=100ms ``` 总结解决方案: 1. 检查`spring.redis.lettuce`下的配置,特别是`shutdown-timeout`的格式。 2. 确保所有属性名称正确。 3. 添加配置处理器依赖并重新构建项目。 4. 如果问题依旧,检查Spring Boot版本,并查阅对应版本的官方文档。 如果以上步骤不能解决问题,请提供具体的配置片段和Spring Boot版本,以便进一步分析。 生成相关问题: 1. 如何正确配置Spring Boot中的Redis连接池参数? 2. Spring Boot中配置属性绑定失败常见的原因有哪些? 3. 如何为Spring Boot自定义配置属性类型转换器? 4.Spring Boot中,如何解决`ConverterNotFoundException`错误? 5. Spring BootRedis的Lettuce客户端有哪些可配置属性?</think>### Spring BootRedis配置属性绑定失败问题解决 针对您遇到的错误信息:`Failed to bind properties under &#39;spring.redis.lettuce&#39; to RedisProperties$Lettuce: ConverterNotFoundException`,以下是系统性的解决方案: #### 问题原因分析 1. **类型转换失败**:配置属性值无法自动转换为目标数据类型(如将字符串转换为复杂对象)[^2] 2. **配置格式错误**:`application.properties`或`application.yml`中的属性语法不符合Spring Boot要求 3. **依赖缺失**:缺少必要的配置处理器依赖 4. **属性名不匹配**:配置属性与`RedisProperties$Lettuce`类的字段名不一致 5. **版本兼容问题**:Spring Boot版本与Redis客户端库存在兼容性问题 #### 解决方案 ##### 1. 检查配置语法(关键步骤) 在`application.properties`中确保使用**正确格式**: ```properties # 正确示例(注意短横线命名法) spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.min-idle=0 spring.redis.lettuce.shutdown-timeout=100ms ``` 或在`application.yml`中: ```yaml spring: redis: lettuce: pool: max-active: 8 max-idle: 8 min-idle: 0 shutdown-timeout: 100ms ``` ##### 2. 添加配置处理器依赖 在`pom.xml`中添加: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> ``` 重新构建项目(`mvn clean install`)以生成配置元数据[^3]。 ##### 3. 验证属性名称匹配 检查配置属性是否匹配`RedisProperties.Lettuce`类的实际字段(Spring Boot 2.7+): - `pool.maxActive` → 配置文件中应为`max-active` - `shutdownTimeout` → 配置文件中应为`shutdown-timeout` ##### 4. 检查数据类型一致性 确保复杂属性(如`shutdown-timeout`)使用Spring Boot支持的格式: ```properties # 正确的时间单位格式 spring.redis.lettuce.shutdown-timeout=200ms # 支持ms/s/m # 错误示例(会导致ConverterNotFoundException) spring.redis.lettuce.shutdown-timeout=200 ``` ##### 5. 版本兼容性处理 若使用Spring Boot 2.3+,在`pom.xml`中显式指定Lettuce版本: ```xml <properties> <lettuce.version>6.1.8.RELEASE</lettuce.version> </properties> ``` #### 验证步骤 1. 启动时添加调试参数: ```bash java -jar your-app.jar --debug ``` 2. 在日志中搜索`RedisProperties`确认绑定结果 3. 使用`@ConfigurationPropertiesScan`注解确保配置类被扫描到 #### 预防措施 - 使用IDE的Spring配置提示功能(如IntelliJ的YAML/Properties自动补全) - 定期运行`spring-boot-configuration-processor`生成元数据 - 复杂对象属性建议使用YAML格式提高可读性 > **补充说明**:该错误常发生在从Spring Boot 1.x升级到2.x时,因配置属性命名规则从驼峰式改为短横线式导致[^4]。若问题仍未解决,请提供完整的配置片段和Spring Boot版本信息以便进一步分析。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值