fabric-sdk-java 提交事务

在之前的文章“fabric sdk java 简单示例” 中运行了一个示例项目(基于 fabric-sample 中的fabcar示例,其中有 queryAllCars 调用的示例,下面在添加2个新的示例方法:

1. queryCar 根据 key 查询某条数据

static void queryCar(HFClient client) throws ProposalException, InvalidArgumentException {
        // get channel instance from client
        Channel channel = client.getChannel("mychannel");
        // create chaincode request
        QueryByChaincodeRequest qpr = client.newQueryProposalRequest();
        // build cc id providing the chaincode name. Version is omitted here.
        ChaincodeID fabcarCCId = ChaincodeID.newBuilder().setName("fabcar").build();
        qpr.setChaincodeID(fabcarCCId);
        // CC function to be called
        qpr.setFcn("queryCar");
        String[] args = new String[] {"CAR1"};
        qpr.setArgs(args);
        Collection res = channel.queryByChaincode(qpr);
        // display response
        for (ProposalResponse pres : res) {
            String stringResponse = new String(pres.getChaincodeActionResponsePayload());
            log.info(stringResponse);
        }
}

2. createCar 新建数据

static void createCar(HFClient client) throws Exception {
        Channel channel = client.getChannel("mychannel");
        TransactionProposalRequest tpr = client.newTransactionProposalRequest();
        ChaincodeID cid = ChaincodeID.newBuilder().setName("fabcar").build();
        tpr.setChaincodeID(cid);
        tpr.setFcn("createCar");
        tpr.setArgs(new String[]{"CAR11", "Skoda", "MB1000", "Yellow", "Lukas"});
        Collection responses = channel.sendTransactionProposal(tpr);
        List invalid = responses.stream().filter(r -> r.isInvalid()).collect(Collectors.toList());
        if (!invalid.isEmpty()) {
            invalid.forEach(response -> {
                log.error(response.getMessage());
            });
            throw new RuntimeException("invalid response(s) found");
        }
        BlockEvent.TransactionEvent event =  channel.sendTransaction(responses).get(60, TimeUnit.SECONDS);
        if (event.isValid()) {
            System.out.println("--- Transacion tx: " + event.getTransactionID() + " is completed.");
        } else {
            System.out.println("--- Transaction tx: " + event.getTransactionID() + " is invalid.");
        }
}

你可能感兴趣的:(fabric-sdk-java 提交事务)