pom依赖:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> <relativePath/> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> </dependencies>
yml配置:
1 spring: 2 redis: 3 host: 127.0.0.1
配置类:
/**
* @author GongXincheng
* @since 2019-09-26 13:36
*/
@Configuration
public class RedisConfigBean {
/**
* redis 防止key value 前缀乱码.
*
* @param factory redis连接 factory
* @return redisTemplate
*/
@Bean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
常用api:
stringRedisTemplate.opsForValue().set("test", "100",60*10,TimeUnit.SECONDS);//向redis里存入数据和设置缓存时间 stringRedisTemplate.opsForValue().get("test") //根据key获取缓存中的val stringRedisTemplate.boundValueOps("test").increment(-1); //val做-1操作 stringRedisTemplate.boundValueOps("test").increment(1); //val +1 stringRedisTemplate.getExpire("test") //根据key获取过期时间 stringRedisTemplate.getExpire("test",TimeUnit.SECONDS) //根据key获取过期时间并换算成指定单位 stringRedisTemplate.delete("test"); //根据key删除缓存 stringRedisTemplate.hasKey("546545"); //检查key是否存在,返回boolean值 stringRedisTemplate.expire("red_123",1000 , TimeUnit.MILLISECONDS); //设置过期时间 stringRedisTemplate.opsForSet().add("red_123", "1","2","3"); //向指定key中存放set集合 stringRedisTemplate.opsForSet().isMember("red_123", "1") //根据key查看集合中是否存在指定数据 stringRedisTemplate.opsForSet().members("red_123"); //根据key获取set集合