赞
踩
springboot集成redis手把手,每一步配图。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.6.11</version>
</dependency>
<!-- spring web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
这里需要注意的是由于本人引用的是2.6版本的redis在配置的时候发现需要多一个data。于是翻阅1版本下的redis源码发现在redisProeperties类中如下配置有所差异。
下图是2.6.11版本中的配置情况
# Redis 数据库索引(默认为0) spring.data.redis.database=0 # Redis 服务的ip,我的是在虚拟机的服务器上。 spring.data.redis.host=192.168.45.129 # Redis 端口 spring.data.redis.port=6379 # Redis 密码,默认为空,可以修改 redis.conf配置文件 spring.data.redis.password= # 最大可用连接数 spring.redis.pool.max-active=200 # 从连接池中获取连接最大等待时间 spring.redis.pool.max-wait=-1 # 最大空闲连接数 spring.redis.pool.max-idle=10 # 最小空闲连接数 spring.redis.pool.min-idle=0 # redis连接超时时间(单位为毫秒) spring.data.redis.timeout=1000
@RestController
public class StudentController {
@Resource
private RedisTemplate redisTemplate; // 注入redis对象,必须是这个变量名
@GetMapping("/saveStu")
public void setStudent(){
redisTemplate.opsForValue().set("st2","6663");
}
}
注意:
@Autowird注解是按照类型注入的,即Spring容器中的bean的class,@Resource是按照Spring容器中的id 名自动注入的在Springboot这种使用redis,Spring容器中存在两个redis对象:RedisTmplate 和 StringRedisTemplate,程序在编译完成以后,会消除泛型的指定,最后程序中会出现两个 一样的RedisTemplate对象。
**稍不注意就会出现如下错误:
从源码可以得知
通过上述配置可以实现简单的写入redis数据,也是笔者踩过的一些坑,后续还会继续添加新的内容。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。