一:配置
1.pox.xml引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置环境
spring:
redis:
host: (ip)
port: (端口,默认6379)
database: (0 - 16库)
二:常用api
StringRedisTemplate
@Autowired
private StringRedisTemplate stringRedisTemplate;
1.key相关操作
//查看所有的key
stringRedisTemplate.keys("*");
2.设置key的过期时间
//参数一:时间 参数二:时间 参数三:时间单位
stringRedisTemplate.expire("name",10, TimeUnit.HOURS);
3.获取key过期时间
stringRedisTemplate.getExpire("name");
4.string list set zset hash相关
//string类型操作
ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
stringStringValueOperations.set("name","6666");
String s = stringStringValueOperations.get("name");
System.out.println(s); //6666
stringRedisTemplate.opsForList();//LIST类型操作
stringRedisTemplate.opsForSet();//set
stringRedisTemplate.opsForZSet();//zset
stringRedisTemplate.opsForHash();//hash
5.使用绑定key操作
BoundValueOperations<String, String> name = stringRedisTemplate.boundValueOps("name");//绑定字符串类型的key
name.append("99999");
String s = name.get();
System.out.println(s);//666699999
stringRedisTemplate.boundListOps("names");
stringRedisTemplate.boundSetOps("Sets");
stringRedisTemplate.boundZSetOps("ZSets");
stringRedisTemplate.boundHashOps("Hashs");
RedisTemplate
注意:redisTemplate默认使用key序列化方式 和 value的序列化方式都是使用的jdk Serializer序列化
1.key相关操作
//entity
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
@Data
@Accessors(chain =true)
public class User implements Serializable {
private String id;
private String name;
private Date bir;
}
//测试类里
@Autowired
private RedisTemplate redisTemplate;
@Test
void t(){
User user = new User();
user.setId(UUID.randomUUID().toString()).setName("ck").setBir(new Date());
redisTemplate.opsForValue().set("user",user);
User user1 = (User) redisTemplate.opsForValue().get("user");
System.out.println(user);
}
2.自定义序列化
//设置key的序列化 字符串的序列化方式
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置value的序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
//为了保证jackson反序列化成功必须转换对象类型一并存储到json中以便日后反序列化
ObjectMapper objectMapper = new ObjectMapper();
//转换json时将原始类型保留在json中
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//修改entity保存的日期格式
objectMapper.setDateFormat(new SimpleDateFormat("yyyy年MM月dd"));
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);