1. 程式人生 > >SpringBoot區塊鏈之以太坊區塊高度掃描(簡潔版)

SpringBoot區塊鏈之以太坊區塊高度掃描(簡潔版)

繼續昨天的demo往下寫寫:[SpringBoot區塊鏈之以太坊開發(整合Web3j)](https://juejin.im/post/5d88e6c1518825094f69e887),將複雜的邏輯都去除了,留下最簡單區塊高度掃描部分程式碼,這樣更好讓開發者上手 首先自定義個區塊高度處理執行緒類 ``` package com.xiaobin.ethdemo.component; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.methods.response.EthBlockNumber; /** * 建立時間: 2019/9/24 23:08 * 備註: * 碼農自學交流小群:260532022,歡迎大家的加入,分享學習是一件開心事 **/ @Component public class EthWatcher implements Runnable { @Autowired private Web3j web3j; // 是否停止掃描 private boolean stop = false; // 當前區塊高度 private Long currentBlockHeight = 8612532L; // 等待掃描事件 private Long checkInterval = 5000L; //區塊確認數 private int confirmation = 1; // 每次掃描區塊的數量 private int step = 5; public void check() { try { Long networkBlockNumber = getNetworkBlockHeight() - confirmation + 1; System.out.println(networkBlockNumber); currentBlockHeight = (networkBlockNumber - currentBlockHeight > step) ? currentBlockHeight + step : networkBlockNumber; System.out.println("掃描當前區塊高度:"+currentBlockHeight); System.out.println("當前網路區塊高度:"+networkBlockNumber); } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { stop = false; long nextCheck = 0; while (!(Thread.interrupted() || stop)) { if (nextCheck <= System.currentTimeMillis()) { try { nextCheck = System.currentTimeMillis() + checkInterval; check(); } catch (Exception ex) { } } else { try { Thread.sleep(Math.max(nextCheck - System.currentTimeMillis(), 100)); } catch (InterruptedException ex) { } } } } public Long getNetworkBlockHeight() { try { EthBlockNumber blockNumber = web3j.ethBlockNumber().send(); return blockNumber.getBlockNumber().longValue(); } catch (Exception e) { e.printStackTrace(); return 0L; } } } ``` 然後啟動就ok拉,我這裡使用的使用@PostConstruct註解,也可以在Spring容器載入時啟動,都可以的 ``` @Autowired private EthWatcher ethWatcher; @PostConstruct public void start(){ new Thread(ethWatcher).start(); } ``` 效果圖 ![file](https://img2018.cnblogs.com/blog/1602984/201909/1602984-20190924234222039-734798454.jpg) 我們可以通過區塊高度獲取到每筆交易的詳情資訊,然後進行處理,這裡的邏輯就需要自己寫拉,Get請求例子例子 ``` @GetMapping("/test") pub