请在springboot里面配置一个redis来缓存一个以 Token 为 Key,用户信息为 Value
时间: 2023-05-20 17:05:44 浏览: 184
可以在 Spring Boot 中使用以下代码配置 Redis 缓存:
1. 添加 Redis 依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 在 application.properties 文件中配置 Redis:
```properties
# Redis 配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0
```
3. 创建 Redis 配置类:
```java
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(30))
.disableCachingNullValues()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(redisCacheConfiguration)
.build();
}
}
```
4. 在需要缓存的方法上添加 @Cacheable 注解:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
@Cacheable(value = "user", key = "#token")
public User getUserByToken(String token) {
User user = (User) redisTemplate.opsForValue().get(token);
if (user == null) {
user = userRepository.findByToken(token);
redisTemplate.opsForValue().set(token, user);
}
return user;
}
}
```
以上代码将以 Token 为 Key,用户信息为 Value 进行缓存。
阅读全文