ChannelGroup.java
1.63 KB
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
package com.viontech.netty;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author 谢明辉
*/
@Slf4j
public class ChannelGroup {
/** 设备序列号和最后心跳的映射 */
public static final Map<String, Long> HEART_BEAT_MAP = new LinkedHashMap<>();
private static final Lock LOCK = new ReentrantLock();
/** 设备序列号和通道id的映射 */
private static final Map<Long, Channel> DEVICE_CHANNEL_MAP = new LinkedHashMap<>();
/**
* 设备注册
*
* @param deviceId 设备ID
* @param channel 通道
*/
public static void registered(Long deviceId, Channel channel) {
LOCK.lock();
try {
DEVICE_CHANNEL_MAP.put(deviceId, channel);
} finally {
LOCK.unlock();
}
log.info("设备注册成功:{}", deviceId);
}
/**
* @param deviceId 设备ID
* @param msg 要发送的消息
*/
public static void sendMessage(Long deviceId, Object msg) {
Channel channel = DEVICE_CHANNEL_MAP.get(deviceId);
try {
channel.writeAndFlush(msg).await();
} catch (Exception ignored) {
}
}
/**
* 广播消息
*
* @param msg 消息
*/
public static void broadcast(Object msg) {
for (Channel channel : DEVICE_CHANNEL_MAP.values()) {
try {
channel.writeAndFlush(msg).await();
} catch (Exception ignored) {
}
}
}
}