标签:mil math start class response override current inter pac
继续昨天的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") public List标签:mil math start class response override current inter pac
原文地址:https://www.cnblogs.com/hy-xiaobin/p/11581946.html