通过Spring的依赖注入将web3j集成到Spring Boot应用程序中。此处提供了示例应用程序:package org.web3j.examples;import java.io.IOExcep
通过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)@SpringBootTestpublic 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实例,如果你需要它们:
@Autowiredprivate Web3j web3j;
如果要通过HTTP连接到默认URLhttp://localhost:8545
,则无需其他配置。
否则,只需在应用程序属性中添加端点的地址:
# An infura endpointweb3j.client-address = https://rinkeby.infura.io/# Or, an IPC endpoingweb3j.client-address = /path/to/file.ipc
管理客户端
如果你希望使用Parity和Geth共有的personal模块方法管理帐户,启用管理客户端:
web3j.admin-client = true
然后Spring可以注入管理客户端:
@Autowiredprivate Admin admin;
HTTP客户端配置
某些以太坊操作所需的时间超过了web3j使用的OkHttp3库设置的默认HTTP超时。要配置这些超时,请设置web3j httpTimeoutSeconds
属性:
web3j.httpTimeoutSeconds = 600
这将设置所有三个OkHttp3超时:connect
,read
,write
。
有效值是任何非负整数。
如果设置值为“0”表示no timeout
没有超时。
注意:与web3j进行交易不需要这样做。
更多的信息
有关web3j的更多信息,请参阅web3j主页中文版。
分享2个java以太坊、比特币相关的交互式在线编程实战教程:
- java以太坊开发教程,主要是针对java和android程序员进行区块链以太坊开发的web3j详解。
- java比特币开发教程,本课程面向初学者,内容即涵盖比特币的核心概念,例如区块链存储、去中心化共识机制、密钥与脚本、交易与UTXO等,同时也详细讲解如何在Java代码中集成比特币支持功能,例如创建地址、管理钱包、构造裸交易等,是Java工程师不可多得的比特币开发学习课程。
汇智网原创翻译,转载请标明出处。这里是原文如何在Spring Boot中开始web3j开发