redis在spring中的配置及使用
时间: 2023-10-27 22:07:01 浏览: 51
在Spring中使用Redis需要进行以下几步配置:
1. 添加Redis依赖
在`pom.xml`文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 配置Redis连接信息
在`application.properties`或`application.yml`文件中添加以下配置信息:
```properties
spring.redis.host=127.0.0.1 # Redis服务器地址
spring.redis.port=6379 # Redis服务器端口号
spring.redis.password= # Redis服务器密码(如果没有设置密码,则不需要配置)
spring.redis.timeout=10000 # 连接超时时间(毫秒)
spring.redis.database=0 # Redis数据库编号(默认为0)
```
3. 配置RedisTemplate Bean
在Spring Boot中,可以通过自动配置来创建一个RedisTemplate Bean。我们只需要在代码中注入这个Bean,就可以直接使用RedisTemplate来访问Redis服务了。
```java
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
}
```
这里我们使用了`Jackson JSON`库来序列化Redis中的Java对象。需要在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
4. 使用RedisTemplate访问Redis服务
```java
@Service
public class UserService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public User getUser(Long id) {
// 先从缓存中查找用户信息
String key = "user:" + id;
User user = (User) redisTemplate.opsForValue().get(key);
if (user != null) {
return user;
}
// 如果缓存中没有,则从数据库中查找
user = userRepository.findById(id).orElse(null);
if (user != null) {
// 将用户信息存入缓存中
redisTemplate.opsForValue().set(key, user, 1, TimeUnit.MINUTES);
}
return user;
}
}
```
以上就是在Spring中使用Redis的配置和使用方法。