1. 程式人生 > 實用技巧 >Springboot整合redis:bitmaps用法

Springboot整合redis:bitmaps用法

1、統計當前登入使用者數
2、統計近五分鐘的線上裝置數量

@Autowired
private StringRedisTemplate stringRedisTemplate;

/** * 設定bitmaps,統計線上裝置數 * * @param deviceId */ private void setBitmaps(String key, Long deviceId) { try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); //獲取當前時間 String curDate = formatter.format(new Date(System.currentTimeMillis())); redisTemplate.opsForValue().setBit(key + curDate, deviceId, true); } catch (Exception e) { log.error("setBitmaps,deviceId is {}, exception is {}", deviceId, e); } } /** * 統計近五分鐘線上數 */ public void getOnlineCount() { try { String key = "aiot:towercrane:device:online:"; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); //獲取當前時間 String curDate = key + formatter.format(new Date(System.currentTimeMillis())); String curDateBeforeOne = key + formatter.format(new Date(System.currentTimeMillis() - 1 * 60 * 1000L)); String curDateBeforeTwo = key + formatter.format(new Date(System.currentTimeMillis() - 2 * 60 * 1000L)); String curDateBeforeThree = key + formatter.format(new Date(System.currentTimeMillis() - 3 * 60 * 1000L)); String curDateBeforeFour = key + formatter.format(new Date(System.currentTimeMillis() - 4 * 60 * 1000L)); long count = (long) stringRedisTemplate.execute((RedisCallback<Long>) con -> con.bitOp(RedisStringCommands.BitOperation.AND, curDate.getBytes(), curDateBeforeOne.getBytes(), curDateBeforeTwo.getBytes(), curDateBeforeThree.getBytes(), curDateBeforeFour.getBytes())); System.out.println(count); } catch (Exception e) { log.error("getAttendanceOnlineCount exception is {}", e); } }