UDP接收百萬級資料的解決方案,udp接收解決方案

來源:互聯網
上載者:User

UDP接收百萬級資料的解決方案,udp接收解決方案
小序

到新公司不久,就接到一個任務:有個發送方,會通過udp發送一些資訊,然後服務接收到資訊後儲存到資料庫的一張表A,儲存的這些資料在經過一系列處理,處理完成後累積到另一張表B,然後清空處理的表A的資料。目前發送方比較少,不久就要增加到100個。

方案

我採用netty5來進行udp的網路通訊,將接收到的資料儲存到BlockingQueue中,然後讀取BlockingQueue中的資料,取到100條就存到hbase資料庫中。

部分代碼
  • 初始化netty

 

int DEFAULT_PORT = 6000;EventLoopGroup group = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap();bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true).handler(new UdpServerHandler());Channel channel = bootstrap.bind(DEFAULT_PORT).sync().channel();channel.closeFuture().await();LOGGER.info("netty初始化成功!");} catch (InterruptedException e) {e.printStackTrace();} finally {group.shutdownGracefully();}

 

  

 

  • 接收udp資料

 

public BlockingQueue<Map<String, Object>> queue = 
new LinkedBlockingQueue<Map<String, Object>>(990000);protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {// 因為Netty對UDP進行了封裝,所以接收到的是DatagramPacket對象。String result = msg.content().toString(CharsetUtil.UTF_8);Map<String, Object> getMap = new HashMap<String, Object>();//處理資料
queue.put(getMap);
ctx.writeAndFlush(new DatagramPacket(
Unpooled.copiedBuffer("結果:", CharsetUtil.UTF_8), msg.sender()));}

 

  • 讀取資料存hbase
public void getDate() {LOGGER.info("開始取資料");List<Map<String, Object>> jsonList = new ArrayList<Map<String, Object>>();while (true) {Map<String, Object> takeMap = null;try {takeMap = queue.take();if (takeMap == null) {continue;}jsonList.add(takeMap);if (jsonList.size() == 100) {String httpJson = HbaseUtil.toHttpJson(vo.getTableName(), jsonList);LOGGER.info(httpJson);List<HbaseDataEntity> hbaseDatas =ParseJson.getData(httpJson);HbaseAPI.insertDataList(hbaseDatas);jsonList.clear();LOGGER.info("hbase存了100條");}} catch (Exception e) {jsonList.clear();continue;}}}
遇到的坑

 

  • BlockingQueue一定要設定大小,不設定是int最大值,有可能會記憶體溢出;
  • 從BlockingQueue取資料的時候一定要阻塞式取take(),負責會死迴圈,占CPU100%;
  • hbase庫串連時是阻塞式的,如果串連不上會一直阻塞。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.