java sprintboot 连接 redis
时间: 2023-07-11 20:33:21 浏览: 44
如果你正在使用 Spring Boot,连接 Redis 可以使用 Spring Data Redis 提供的自动配置功能,只需在项目中添加相关依赖即可。
以下是连接 Redis 的简单示例。
1. 添加依赖
在 pom.xml 文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 配置 Redis 连接信息
在 application.properties 文件中配置 Redis 连接信息:
```
spring.redis.host=localhost
spring.redis.port=6379
```
3. 使用 RedisTemplate 进行操作
可以使用 RedisTemplate 进行 Redis 操作,例如设置键值对、获取值等。
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, String> redisTemplate;
public void set(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
public String get(String key) {
return redisTemplate.opsForValue().get(key);
}
}
```
在上面的示例中,通过自动注入 RedisTemplate 对象,然后使用 opsForValue() 方法获取 ValueOperations 对象进行操作。
需要注意的是,redisTemplate 的泛型类型需要与 Redis 数据类型对应,例如 opsForValue() 方法返回的 ValueOperations 对象的泛型类型为 <String, String>,表示操作的是 String 类型的 key-value 数据。