在做签到打卡功能时,往往会遇到一个问题,我想要获取用户这个月打卡记录需要怎么做呢?
下面是最常规的做法,循环获取redis key中的偏移值,但是这种写法看着确实不太优雅....
long offset = 0;
for (int i = 0; i < 10; i++) {
redisTemplate.opsForValue().getBit("key", offset);
}
spring-boot-starter-data-redis早就考虑到了这一点,所以为我们提供了一种批量执行命令的方式。
我们需要使用BitFieldSubCommands
private List<Long> getCheckDay(int year, int month) {
//假设有个日期
LocalDate localDate = LocalDate.of(year, month, 1);
BitFieldSubCommands.BitFieldSubCommand[] list = new
//monthArr获取本月天数
BitFieldSubCommands.BitFieldSubCommand[monthArr[month - 1]];
for (int i = 0; i < list.length; i++) {
BitFieldSubCommands.BitFieldGet bitFieldGet = BitFieldSubCommands.BitFieldGet.create(BitFieldSubCommands.BitFieldType.unsigned(1),
BitFieldSubCommands.Offset.offset(i));
list[i] = bitFieldGet;
}
//命令放入BitFieldSubCommands中,批量执行。
BitFieldSubCommands fieldSubCommands = BitFieldSubCommands.create(list);
return redisTemplate.opsForValue().bitField(getCheckInKey(localDate), fieldSubCommands);
}
需要注意,以下写法无效。
需要创建一条一条的BitFieldSubCommand才有效
long[] offsetArray = new long[]{1,3,5,7,9};
BitFieldSubCommands fieldSubCommands = BitFieldSubCommands.create();
for (int i = 0; i < offsetArray.length; i++) {
BitFieldSubCommands subCommands = BitFieldSubCommands.create.get(BitFieldSubCommands.BitFieldType.unsigned(1)).valueAt(offsetArray[i]);
//There is no way to combine multiple commands
}
List<Long> result = redisTemplate.opsForValue().bitField("test",fieldSubCommands);