zxl
2026-03-23 74af7e7e3ee39e25f73525391b13face373e350e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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();
        }
    }
 
}