package com.tievd.jyz.cache;
|
|
import cn.hutool.core.collection.ListUtil;
|
import com.tievd.jyz.entity.Device;
|
import com.tievd.jyz.mapper.DeviceMapper;
|
import org.apache.commons.lang3.ArrayUtils;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.stereotype.Component;
|
|
import javax.annotation.PostConstruct;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.locks.ReadWriteLock;
|
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
|
/**
|
* 网关缓存
|
* @author timi
|
*/
|
@Component
|
public class DeviceCache {
|
|
private final static Map<Long,Device> DEVICE_ID_MAP = new ConcurrentHashMap();
|
private final static Map<String,Device> DEVICE_SN_MAP = new ConcurrentHashMap();
|
private final static ReadWriteLock READ_WRITE_LOCK = new ReentrantReadWriteLock();
|
@Autowired
|
private DeviceMapper deviceMapper;
|
|
@PostConstruct
|
public void init(){
|
READ_WRITE_LOCK.writeLock().lock();
|
try{
|
DEVICE_ID_MAP.clear();
|
DEVICE_SN_MAP.clear();
|
List<Device> devices = deviceMapper.selectList(null);
|
for(Device device : devices){
|
DEVICE_ID_MAP.put(device.getId(),device);
|
DEVICE_SN_MAP.put(device.getSn(),device);
|
}
|
}finally {
|
READ_WRITE_LOCK.writeLock().unlock();
|
}
|
}
|
|
/**
|
* 获取网关列表
|
* @return
|
*/
|
public static List<Device> getDeviceList(){
|
return ListUtil.toList(DEVICE_ID_MAP.values());
|
}
|
|
/**
|
* 获取设备信息
|
* @param sn
|
* @return
|
*/
|
public static Device getDeviceBySn(String sn){
|
READ_WRITE_LOCK.readLock().lock();
|
try {
|
return DEVICE_SN_MAP.get(sn);
|
}finally {
|
READ_WRITE_LOCK.readLock().unlock();
|
}
|
}
|
|
/**
|
* 获取设备信息
|
* @param id
|
* @return
|
*/
|
public static Device getDeviceById(Long id){
|
READ_WRITE_LOCK.readLock().lock();
|
try {
|
return DEVICE_ID_MAP.get(id);
|
}finally {
|
READ_WRITE_LOCK.readLock().unlock();
|
}
|
}
|
|
}
|