引入redis
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
将redis作为缓存
spring.redis.host=127.0.0.1
spring.redis.password=*****
spring.cache.type=redis
spring.cache.redis.cache-null-values=false
spring:
redis:
host: 127.0.0.1
password: 123456
cache:
type: redis
redis:
cache-null-values: false
为要存入到redis中的类进行配置
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<Object, UserPO> personRedisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, UserPO> template = new RedisTemplate<Object, UserPO>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<UserPO> serializer = new Jackson2JsonRedisSerializer<UserPO>(UserPO.class);
template.setDefaultSerializer(serializer);
return template;
}
}
redis中几个常用的代码
@Autowired
private RedisTemplate<Object, UserPO> redisTemplate;
//将对象以json格式存入redis,并设置过期时间
redisTemplate.opsForValue().set("k",person, Duration.ofHours(23L));
//获取redis中键为“K”的值
redisTemplate.opsForValue().get("k");
//删除redis中键为"k"的键值对
redisTemplate.delete("k");
//重置redis中键为"k"的键值对的过期时间
redisTemplate.expire("k",30L,TimeUnit.MINUTES);
token
//生成令牌
String Token = UUID.randomUUID()+"";
//从HTTP请求中获取Token,存在与请求的headler中
String Token = request.getHeader("Token");
//将Token作为键存入redis,并设置过期时间
redisTemplate.opsForValue().set(Token,对象, Duration.ofHours(23L));