您现在的位置是:首页 > 文章详情

如何在Spring Boot中开始web3j开发以太坊

日期:2018-11-26点击:487

通过Spring的依赖注入将web3j集成到Spring Boot应用程序中。此处提供了示例应用程序:

package org.web3j.examples; import java.io.IOException; import org.apache.http.conn.HttpHostConnectException; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest public class SpringBootWeb3jSampleApplicationTest { @Autowired private Web3jSampleService web3jSampleService; // This test will only run if you provide a real Ethereum client for web3j to connect to @Test(expected = HttpHostConnectException.class) public void testGetClientVersion() throws IOException { assertThat(web3jSampleService.getClientVersion()).startsWith("Geth/"); } } 

要使用这个github示例,请创建一个新的Spring Boot应用程序,并包含以下依赖项:

Maven:

<dependency> <groupId>org.web3j</groupId> <artifactId>web3j-spring-boot-starter</artifactId> <version>1.6.0</version> </dependency> 

Gradle:

compile ('org.web3j:web3j-spring-boot-starter:1.6.0') 

现在,Spring可以为你提供web3j实例,如果你需要它们:

@Autowired private Web3j web3j; 

如果要通过HTTP连接到默认URLhttp://localhost:8545,则无需其他配置。

否则,只需在应用程序属性中添加端点的地址:

# An infura endpoint web3j.client-address = https://rinkeby.infura.io/ # Or, an IPC endpoing web3j.client-address = /path/to/file.ipc 

管理客户端

如果你希望使用Parity和Geth共有的personal模块方法管理帐户,启用管理客户端:

web3j.admin-client = true 

然后Spring可以注入管理客户端:

@Autowired private Admin admin; 

HTTP客户端配置

某些以太坊操作所需的时间超过了web3j使用的OkHttp3库设置的默认HTTP超时。要配置这些超时,请设置web3j httpTimeoutSeconds属性:

web3j.httpTimeoutSeconds = 600 

这将设置所有三个OkHttp3超时:connectreadwrite

有效值是任何非负整数。

如果设置值为“0”表示no timeout没有超时。

注意:与web3j进行交易不需要这样做。

更多的信息

有关web3j的更多信息,请参阅web3j主页中文版

分享2个java以太坊、比特币相关的交互式在线编程实战教程:

  • java以太坊开发教程,主要是针对java和android程序员进行区块链以太坊开发的web3j详解。
  • java比特币开发教程,本课程面向初学者,内容即涵盖比特币的核心概念,例如区块链存储、去中心化共识机制、密钥与脚本、交易与UTXO等,同时也详细讲解如何在Java代码中集成比特币支持功能,例如创建地址、管理钱包、构造裸交易等,是Java工程师不可多得的比特币开发学习课程。

汇智网原创翻译,转载请标明出处。这里是原文如何在Spring Boot中开始web3j开发

原文链接:https://my.oschina.net/u/2472105/blog/2960954
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章