redis-spring-boot-starter
时间: 2025-02-25 18:07:19 浏览: 44
### 如何使用 `redis-spring-boot-starter` 进行 Redis 和 Spring Boot 的集成配置
#### 添加依赖
为了使项目能够访问并操作 Redis 数据库,在项目的构建文件中需引入特定的 starter 依赖。对于 Maven 构建工具而言,应在 pom.xml 文件内加入如下所示的内容:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
值得注意的是,存在两种不同的 Starter 可供选择:“`spring-boot-starter-data-redis`”以及“`spring-boot-starter-redis`”。前者包含了后者,并额外提供了更多高级特性支持,因此推荐优先考虑使用 “`spring-boot-starter-data-redis`”,除非有特殊需求[^2]。
#### 配置连接参数
完成上述依赖添加之后,则需要通过 application.properties 或者 application.yml 来指定与目标 Redis 实例建立网络通信所需的信息,比如主机地址、端口号等基本信息设置如下:
如果采用 properties 方式:
```properties
# Redis服务器地址,默认localhost
spring.redis.host=127.0.0.1
# Redis服务器连接端口,默认6379
spring.redis.port=6379
# 设置密码(如果有)
spring.redis.password=mypassword
```
若是 yml 格式的配置则为:
```yaml
spring:
redis:
host: 127.0.0.1
port: 6379
password: mypassword
```
以上配置均来源于官方文档说明[^1]。
#### 编写业务逻辑代码
最后一步就是在具体的 Java 类里面编写实际处理数据存取的操作方法了。这里给出一个简单的例子来展示如何利用 JedisTemplate 对象来进行基本的数据读写动作:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Autowired
private StringRedisTemplate template;
public void setValue(String key, String value){
this.template.opsForValue().set(key,value);
}
public String getValue(String key){
return this.template.opsForValue().get(key);
}
}
```
此段代码展示了怎样注入 `StringRedisTemplate` 并调用其提供的 API 完成键值对形式的数据存储和检索工作。
阅读全文
相关推荐


















