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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
|
@Component @Slf4j public class ClusterConnectionManager {
@Autowired private NettyServerConfig config; @Autowired private RedisTemplate<String, Object> redisTemplate; private final Map<String, Channel> clusterChannels = new ConcurrentHashMap<>(); private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
@PostConstruct public void init() { connectToClusterNodes(); startHeartbeat(); startStatusSync(); }
private void connectToClusterNodes() { for (String nodeAddress : config.getClusterNodes()) { if (isCurrentNode(nodeAddress)) { continue; } try { connectToNode(nodeAddress); } catch (Exception e) { log.error("连接到集群节点失败: nodeAddress={}, error={}", nodeAddress, e.getMessage(), e); } } }
private void connectToNode(String nodeAddress) { String[] parts = nodeAddress.split(":"); String host = parts[0]; int port = Integer.parseInt(parts[1]); EventLoopGroup group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new LengthFieldBasedFrameDecoder(65535, 0, 4, 0, 4)); pipeline.addLast(new LengthFieldPrepender(4)); pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8)); pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8)); pipeline.addLast(new ClusterChannelHandler()); } }); ChannelFuture future = bootstrap.connect(host, port); future.addListener((ChannelFutureListener) f -> { if (f.isSuccess()) { clusterChannels.put(nodeAddress, f.channel()); log.info("连接到集群节点成功: nodeAddress={}", nodeAddress); } else { log.error("连接到集群节点失败: nodeAddress={}", nodeAddress); } }); }
private boolean isCurrentNode(String nodeAddress) { String currentAddress = getCurrentNodeAddress(); return currentAddress.equals(nodeAddress); }
private String getCurrentNodeAddress() { try { String host = InetAddress.getLocalHost().getHostAddress(); return host + ":" + config.getPort(); } catch (Exception e) { return "localhost:" + config.getPort(); } }
private void startHeartbeat() { scheduler.scheduleAtFixedRate(() -> { try { sendHeartbeat(); } catch (Exception e) { log.error("发送心跳失败: error={}", e.getMessage(), e); } }, 5, 10, TimeUnit.SECONDS); }
private void sendHeartbeat() { ClusterMessage message = new ClusterMessage(); message.setType("HEARTBEAT"); message.setNodeId(config.getNodeId()); message.setTimestamp(System.currentTimeMillis()); broadcastMessage(message); String key = "netty:cluster:node:" + config.getNodeId(); redisTemplate.opsForValue().set(key, message, 30, TimeUnit.SECONDS); }
private void startStatusSync() { scheduler.scheduleAtFixedRate(() -> { try { syncConnectionStatus(); } catch (Exception e) { log.error("同步连接状态失败: error={}", e.getMessage(), e); } }, 10, 30, TimeUnit.SECONDS); }
private void syncConnectionStatus() { int connectionCount = getConnectionCount(); String key = "netty:cluster:status:" + config.getNodeId(); Map<String, Object> status = new HashMap<>(); status.put("nodeId", config.getNodeId()); status.put("connectionCount", connectionCount); status.put("updateTime", System.currentTimeMillis()); redisTemplate.opsForHash().putAll(key, status); redisTemplate.expire(key, 60, TimeUnit.SECONDS); }
private int getConnectionCount() { return 0; }
public void broadcastMessage(ClusterMessage message) { String messageStr = JSON.toJSONString(message); for (Map.Entry<String, Channel> entry : clusterChannels.entrySet()) { Channel channel = entry.getValue(); if (channel != null && channel.isActive()) { channel.writeAndFlush(messageStr); } } }
public List<String> getClusterNodes() { return new ArrayList<>(clusterChannels.keySet()); } }
@Slf4j public class ClusterChannelHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { String message = (String) msg; ClusterMessage clusterMessage = JSON.parseObject(message, ClusterMessage.class); handleClusterMessage(clusterMessage); } private void handleClusterMessage(ClusterMessage message) { switch (message.getType()) { case "HEARTBEAT": log.debug("收到心跳消息: nodeId={}", message.getNodeId()); break; case "STATUS_SYNC": log.debug("收到状态同步消息: nodeId={}", message.getNodeId()); break; default: log.warn("未知的集群消息类型: type={}", message.getType()); } } }
|