![cc1248b6201a051cced38f5434d5628d.png](https://i-blog.csdnimg.cn/blog_migrate/1571e634e71647ee1752d83f4ba1d4e6.jpeg)
一. 背景
最近的一个项目:我们的系统接收到上游系统的派单任务后,会推送到指定的门店的相关设备,并进行相应的业务处理。
二. Netty 的使用
在接收到派单任务之后,通过 Netty 推送到指定门店相关的设备。在我们的系统中 Netty 实现了消息推送、长连接以及心跳机制。
![3b7fc51cf3d1bcc71591e7b66d114c71.png](https://i-blog.csdnimg.cn/blog_migrate/e905a16accc9e1f4f0dd34e67f0103e9.jpeg)
Netty+ZK.png
2.1 Netty Server 端:
每个 Netty 服务端通过 ConcurrentHashMap 保存了客户端的 clientId 以及它连接的 SocketChannel。
服务器端向客户端发送消息时,只要获取 clientId 对应的 SocketChannel,往 SocketChannel 里写入相应的 message 即可。
EventLoopGroup boss = new NioEventLoopGroup(1); EventLoopGroup worker = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 128) .option(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_KEEPALIVE, true) .childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel channel) throws Exception { ChannelPipeline p = channel.pipeline(); p.addLast(new MessageEncoder()); p.addLast(new MessageDecoder()); p.addLast(new PushServerHandler()); } }); ChannelFuture future = bootstrap.bind(host,port).sync(); if (future.isSuccess()) { logger.info("server start..."); }
2.2 Netty Client 端:
客户端用于接收服务端的消息,随即进行业务处理。客户端还有心跳机制,它通过 IdleEvent 事件定时向服务端放送 Ping 消息以此来检测 SocketChannel 是否中断。
public PushClientBootstrap(String host, int port) throws InterruptedException { this.host = host; this.port = port; start(host,port); } private void start(String host, int port) throws InterruptedException { bootstrap = new Bootstrap(); bootstrap.channel(NioSocketChannel.class) .option(ChannelOption.SO_KEEPALIVE, true) .group(workGroup) .remoteAddress(host, port) .handler(new ChannelInitializer(){ @Override protected void initChannel(Channel channel) throws Exception { ChannelPipeline p = channel.pipeline(); p.addLast(new IdleStateHandler(20, 10, 0)); // IdleStateHandler 用于检测心跳 p.addLast(new MessageDecoder()); p.addLast(new MessageEncoder()); p.addLast(new PushClientHandler()); } }); doConnect(port, host); } /** * 建立连接,并且可以实现自动重连. * @param port port. * @param host host. * @throws InterruptedException InterruptedException. */ private void doConnect(int port, String host) throws InterruptedException { if (socketChannel != null && socketChannel.isActive()) { return; } final int portConnect = port; final String hostConnect = host; ChannelFuture future = bootstrap.connect(host, port); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture futureListener) throws Exception { if (futureListener.isSuccess()) { socketChannel = (SocketChannel) futureListener.channel(); logger.info("Connect to server successfully!"); } else { logger.info("Failed to connect to server, try connect after 10s"); futureListener.channel().eventLoop().schedule(new Runnable() { @Override public void run() { try { doConnect(portConnect, hostConnect); } catch (InterruptedException e) { e.printStackTrace(); } } }, 10, TimeUnit.SECONDS); } } }).sync(); }
三. 借助 ZooKeeper 实现简单的服务注册与发现
3.1 服务注册
服务注册本质上是为了解耦服务提供者和服务消费者。服务注册是一个高可用强一致性的服务发现存储仓库,主要用来存储服务的api和地址对应关系。为了高可用,服务注册中心一般为一个集群,并且能够保证分布式一致性。目前常用的有 ZooKeeper、Etcd 等等。
![07926da8ea7342565f2f5d5ebec1d4dd.png](https://i-blog.csdnimg.cn/blog_migrate/d269e1cd26da195c64c28a00b6baf2a2.jpeg)
在我们项目中采用了 ZooKeeper 实现服务注册。
public class ServiceRegistry { private static final Logger logger = LoggerFactory.getLogger(ServiceRegistry.class); private CountDownLatch latch = new CountDownLatch(1); private String registryAddress; public ServiceRegistry(String registryAddress) { this.registryAddress = registryAddress; } public void register(String data) { if (data != null) { ZooKeeper zk = connectServer(); if (zk != null) { createNode(zk, data); } } } /** * 连接 zookeeper 服务器 * @return */ private ZooKeeper connectServer() { ZooKeeper zk = null; try { zk = new ZooKeeper(registryAddress, Constants.ZK_SESSION_TIMEOUT, new Watcher() { @Override public void process(WatchedEvent event) { if (event.getState() == Event.KeeperState.SyncConnected) { latch.countDown(); } } }); latch.await(); } catch (IOException | InterruptedException e) { logger.error(