FiscoBcos-javasdk の実装
プロジェクト構造
spring-boot に基づく mvn プロジェクト
- conf チェーン証明書、組織証明書、組織秘密鍵、アカウント
- 契約申込書、solファイル
- アプリケーション-dev.yml
channel-service:
group-id: 1 # sdk实际连接的群组
config-toml:
config-path: classpath:config.toml #区块链集群的配置文件
contract-address:
kVPerson: "0x3cc40ecd5000f58c3458fef29b91114bd5e18da3" #合约地址
- config.toml
[cryptoMaterial]
certPath = "conf"
caCert = "conf/ca.crt" #链证书
sslCert = "conf/sdk.crt" #机构证书
sslKey = "conf/sdk.key" #机构私钥
#enSslCert = "conf/gm/gmensdk.crt" #集群为国密版,则需要配置
#enSslKey = "conf/gm/gmensdk.key"
[network]
peers=["192.168.160.135:20200", "192.168.160.135:20201"] #节点ip:port
[account]
keyStoreDir = "account"
accountFilePath = "conf/0x9ff96dcf17f27ddd643c23bc1236733aa92a1f20.pem"
accountFileFormat = "pem"
accountAddress = "0x9ff96dcf17f27ddd643c23bc1236733aa92a1f20" #账户
- pom.xml
fisco-bcos-java-sdk のバージョン 2.7.1 への参照
証明書のコピー
クラスターのチェーン証明書、組織証明書、および組織の秘密鍵をプロジェクトの conf ファイルにコピーします。
コンソール アカウントの下で、プロジェクトの conf ファイルをコピーします
コンソール展開契約
deploy KVPerson
transaction hash: 0x72908963644b7e897bf03d0a9ddb9f76428f5b1684aee89eb251d0adf15bdb75
contract address: 0x3cc40ecd5000f58c3458fef29b91114bd5e18da3
契約住所のコピー
コントラクト アドレスをプロジェクトの application-dev.yml 構成ファイルにコピーし、コントラクト アドレスを介してコントラクトを読み込み、コントラクト オブジェクトを取得します。
Java ファイルを生成する
- コントラクトは Java ファイルに変換されます
./sol2java.sh com.fish1208.contract ~/console-all/console-A/contracts/solidity/KVPerson.sol ~/console-all/console-A/contracts/console/
- 変換された Java ファイルをプロジェクト com.fish1208.contract パッケージにコピーします。
コード開発
BcosSDKConfig .java
config-toml.toml 構成ファイルから BcosSDK オブジェクトを取得します。
package com.fish1208.bcos.config;
import org.apache.commons.io.FileUtils;
import org.fisco.bcos.sdk.BcosSDK;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import java.io.File;
import java.io.InputStream;
@Configuration
@ConfigurationProperties(prefix = "config-toml")
public class BcosSDKConfig {
private Resource configPath;
@Bean
public BcosSDK getBcosSDK() throws Exception{
return BcosSDK.build(getFilePath(configPath));
}
/**
* 在jar包情况下无法读取配置文件config.toml,需要将配置文件config.toml先放到临时文件夹tmp下
* @param resource
* @return
* @throws Exception
*/
private String getFilePath(Resource resource) throws Exception{
File tempFile = File.createTempFile(resource.getFilename().split("\\.")[0], "." + resource.getFilename().split("\\.")[1]);
InputStream in = resource.getInputStream();
try{
FileUtils.copyInputStreamToFile(in, tempFile);
}finally {
in.close();
}
return tempFile.getPath();
}
public Resource getConfigPath() {
return configPath;
}
public void setConfigPath(Resource configPath) {
this.configPath = configPath;
}
}
ClientConfig .java
application-dev.yml 構成ファイルの channel-service を介して、グループとクライアントの接続を取得します。
package com.fish1208.bcos.config;
import org.fisco.bcos.sdk.BcosSDK;
import org.fisco.bcos.sdk.client.Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "channel-service")
public class ClientConfig {
private Integer groupId;
@Autowired
private BcosSDK sdk;
@Bean
public Client getClient() {
return sdk.getClient(groupId);
}
public Integer getGroupId() {
return groupId;
}
public void setGroupId(Integer groupId) {
this.groupId = groupId;
}
}
契約構成.java
コントラクトをロードしてコントラクト オブジェクトを取得するために使用される application-dev.yml 構成ファイルの contract-address を通じてコントラクト アドレスを取得します。
package com.fish1208.bcos.config;
import com.fish1208.bcos.ContractAddress;
import com.fish1208.contract.KVPerson;
import lombok.extern.slf4j.Slf4j;
import org.fisco.bcos.sdk.client.Client;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "contract-address")
public class ContractConfig {
private String kVPerson;
@Bean
public KVPerson loadImage(Client client){
return KVPerson.load(kVPerson, client, client.getCryptoSuite().getCryptoKeyPair());
}
@Bean
public ContractAddress setAddress(){
log.info("kVPerson={}", kVPerson);
ContractAddress contractAddress = new ContractAddress();
contractAddress.setKVPerson(kVPerson);
return contractAddress;
}
public String getkVPerson() {
return kVPerson;
}
public void setkVPerson(String kVPerson) {
this.kVPerson = kVPerson;
}
}
PersonController .java
コントラクトの set メソッドと get メソッドを呼び出して、チェーンにデータをアップロードし、チェーンのデータをクエリします。
package com.fish1208.controller;
import com.alibaba.fastjson.JSON;
import com.fish1208.common.response.Result;
import com.fish1208.contract.KVPerson;
import lombok.extern.slf4j.Slf4j;
import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple4;
import org.fisco.bcos.sdk.model.TransactionReceipt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigInteger;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/contract/person")
public class PersonController {
@Autowired
private KVPerson person;
/**
*
* @param id
* @return
* @throws Exception
*/
@RequestMapping(value = "/get", method = RequestMethod.GET)
public Result<?> get(@RequestParam String id) throws Exception {
if (person != null) {
log.info("KVPerson address is: {}", person.getContractAddress());
Tuple4<Boolean, String, BigInteger, String> tuple = person.get(id);
return Result.data(tuple);
}
return Result.fail("执行KVPerson合约失败");
}
@RequestMapping(value = "/set", method = RequestMethod.POST)
public Result<?> set(@RequestBody Map<String,Object> param) throws Exception {
if (person != null) {
log.info("KVPerson address is: {}", person.getContractAddress());
String id = (String)param.get("id");
String name = (String) param.get("name");
BigInteger age = BigInteger.valueOf((Integer) param.get("age"));
String sex = (String) param.get("sex");
TransactionReceipt receipt = person.set(id, name, age, sex);
log.info("KVPerson receipt = {}", JSON.toJSONString(receipt));
return Result.data(receipt);
}
return Result.fail("执行KVPerson合约失败");
}
}
プロジェクト開始
呼び出しインターフェース
KVPerson コントラクトの set メソッドを実行する
http://127.0.0.1:7022/contract/person/set
聞く
POST /contract/person/set HTTP/1.1
Content-Type: application/json
{
"id":"1",
"name":"袁洪相",
"age":100,
"sex":"男"
}
KVPerson コントラクト get メソッドを実行する
http://127.0.0.1:7022/contract/person/get?id=1
聞く
GET /contract/person/get HTTP/1.1
id=1
Githubアドレス
https://github.com/hongfish/fish1208-fiscobcos-javasdk