最近公司有个业务:统计设备app的在线状态,写了个心跳,每分钟获取app的状态,主要是分为: (1)内网在线 (2)外网在线 (3)第三方网络 (4)离线。放在集合里,然后我在批量修改每个设备的onlineState的标识状态。这就要动态的批量修改onlineState中的值,但是mybatis并不支持 set onlineState = ? 的修改(onlineState是动态的)。然后通过查阅相关资料,通过mysql的case when then 来实现的。具体的实现如下:
一:mySql Case函数
SELECT SUM(population),
CASE country
WHEN '中国' THEN '亚洲'
WHEN '印度' THEN '亚洲'
WHEN '日本' THEN '亚洲'
WHEN '美国' THEN '北美洲'
WHEN '加拿大' THEN '北美洲'
WHEN '墨西哥' THEN '北美洲'
ELSE '其他' END
FROM Table_A
二:动态批量修改:DeviceMapper.xml
<!-- 批量修改设备在线状态 -->
<update id="updateBatchOnlineState" parameterType="java.util.List">
update t_device
set online_state = case device_no
<foreach collection="list" item="item">
WHEN #{item.deviceNo} THEN #{item.onlineState}
</foreach>
END
where
device_no in
<foreach collection="list" open="(" separator="," close=")" item="device">
#{device.deviceNo}
</foreach>
</update>
三:动态批量修改:DeviceMapper.java
int updateBatchOnlineState(List<Device> list);
四:控制层(xxxxController)
//在线设备编号 前端300秒调用一次 ,服务端640秒认为过期
List<String> deviceNos = DeviceCache.getDeviceNo(640);
List<Device> list = new ArrayList<Device>();
if (CollectionUtils.isNotEmpty(deviceNos)) {
for (String str : deviceNos) {
Device device = new Device();
int indexOf = str.lastIndexOf("-");
String deviceNo = str.substring(0, indexOf);
String type = str.substring(indexOf+1, str.length());
device.setDeviceNo(deviceNo);
device.setOnlineState(Integer.valueOf(type));
list.add(device);
}
int row = deviceService.updateBatchOnlineState(list);
if (row < 1) {
logger.debug("批量修改失败!");
} else {
logger.debug("批量修改成功,已实时获取设备在线状态!");
}
} else {
logger.debug("目前没有设备在线!");
deviceService.modifyAllNotOnline();
}
五、最后,欢迎大家关注【码农新锐】公众号,加入我们一起来进阶Java。