继续昨天的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 test() throws Exception{
List list = new ArrayList();
EthBlockNumber blockNumber = web3j.ethBlockNumber().send();
long blockHeight = blockNumber.getBlockNumber().longValue();
EthBlock block = web3j.ethGetBlockByNumber(new DefaultBlockParameterNumber(blockHeight), true).send();

block.getBlock().getTransactions().stream().forEach(transactionResult -> {
EthBlock.TransactionObject transactionObject = (EthBlock.TransactionObject) transactionResult;
Transaction transaction = transactionObject.get();
list.add(transaction);
});
return list;
}
“`
效果图
![file](https://img2018.cnblogs.com/blog/1602984/201909/1602984-20190924234222330-1285726201.jpg)
码云地址:https://gitee.com/MyXiaoXiaoBin/learning-to-share/tree/master/eth-demo

###### 码农自学交流小群:260532022,欢迎大家的加入,分享学习是一件开心事

版权声明:本文为hy-xiaobin原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/hy-xiaobin/p/11581946.html