五、Fabric2.4.6 在java應(yīng)用訪問智能合約(ubuntu 22.04)

四、Fabric2.4.6 智能合約(java)(ubuntu 22.04)

1、pom.xml 引入依賴
# pom.xml中加入fabric依賴
        <dependency>
            <groupId>org.hyperledger.fabric-sdk-java</groupId>
            <artifactId>fabric-sdk-java</artifactId>
            <version>2.2.12</version>
        </dependency>
        <dependency>
            <groupId>org.hyperledger.fabric</groupId>
            <artifactId>fabric-gateway</artifactId>
            <version>1.0.1</version>
        </dependency>
2、拷貝crypto-config
# 拷貝身份信息文件 crypto-config 到resources目錄下
3、用戶身份配置
# application.properties
# 下面配置是用哪個用戶連接到網(wǎng)絡(luò)

fabric.mspId=Org1MSP

# 證書路徑
fabric.certificatePath=src/main/resources/crypto-config/peerOrganizations/org1.supervisor.com/users/User1@org1.supervisor.com/msp/signcerts/User1@org1.supervisor.com-cert.pem
# 私鑰路徑
fabric.privateKeyPath=src/main/resources/crypto-config/peerOrganizations/org1.supervisor.com/users/User1@org1.supervisor.com/msp/keystore/priv_sk
# tls證書路徑
fabric.tlsCertPath=src/main/resources/crypto-config/peerOrganizations/org1.supervisor.com/peers/peer0.org1.supervisor.com/tls/ca.crt
# 通道
fabric.channel=mychannel

logging.level.org.hyperledger=trace

4、增加屬性類
# 在FabricContractApiApplication 啟動類,需要加入@EnableConfigurationProperties注解,否則程序啟動讀取不到appliation.properties屬性;

@Configuration
@ConfigurationProperties(prefix = "fabric")
@Data
public class HyperLedgerFabricProperties {

    String mspId;

    String certificatePath;

    String privateKeyPath;

    String tlsCertPath;

    String channel;

}
5、gateway配置
@Configuration
@AllArgsConstructor
@Slf4j
public class HyperLedgerFabricGatewayConfig {

    @Autowired
    final HyperLedgerFabricProperties hyperLedgerFabricProperties;

    @Bean
    public Gateway gateway() throws Exception {

        BufferedReader certificateReader = Files.newBufferedReader(Paths.get(hyperLedgerFabricProperties.getCertificatePath()), StandardCharsets.UTF_8);

        X509Certificate certificate = Identities.readX509Certificate(certificateReader);

        BufferedReader privateKeyReader = Files.newBufferedReader(Paths.get(hyperLedgerFabricProperties.getPrivateKeyPath()), StandardCharsets.UTF_8);

        PrivateKey privateKey = Identities.readPrivateKey(privateKeyReader);

        Gateway gateway = Gateway.newInstance()
                .identity(new X509Identity(hyperLedgerFabricProperties.getMspId() , certificate))
                .signer(Signers.newPrivateKeySigner(privateKey))
                .connection(newGrpcConnection())
                .evaluateOptions(CallOption.deadlineAfter(5, TimeUnit.SECONDS))
                .endorseOptions(CallOption.deadlineAfter(15, TimeUnit.SECONDS))
                .submitOptions(CallOption.deadlineAfter(5, TimeUnit.SECONDS))
                .commitStatusOptions(CallOption.deadlineAfter(1, TimeUnit.MINUTES))
                .connect();

        log.info("=========================================== connected fabric gateway {} " , gateway);

        return gateway;
    }

    private ManagedChannel newGrpcConnection() throws IOException, CertificateException {
        Reader tlsCertReader = Files.newBufferedReader(Paths.get(hyperLedgerFabricProperties.getTlsCertPath()));
        X509Certificate tlsCert = Identities.readX509Certificate(tlsCertReader);
        // fabric 2.4以后,支持連接一個節(jié)點即可;
        return NettyChannelBuilder.forTarget("peer0.org1.supervisor.com:7051")
                .sslContext(GrpcSslContexts.forClient().trustManager(tlsCert).build())
                .overrideAuthority("peer0.org1.supervisor.com")
                .build();
    }

    @Bean
    public Network network(Gateway gateway) {
        return gateway.getNetwork(hyperLedgerFabricProperties.getChannel());
    }

    @Bean
    public Contract hashInfoContract(Network network) {
        // fabric-smart-contract 鏈碼
        // HashInfoContract 合約
        return network.getContract("fabric-smart-contract" , "HashInfoContract");
    }

    @Bean
    public ChaincodeEventListener chaincodeEventListener(Network network) {
        return new ChaincodeEventListener(network);
    }
}
6、事件監(jiān)聽
@Slf4j
public class ChaincodeEventListener implements Runnable{

    final Network network;

    public ChaincodeEventListener(Network network) {
        this.network = network;

        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setDaemon(true);
                thread.setName(this.getClass() + "chaincode_event_listener");
                return thread;
            }
        });

        executor.execute(this);
    }

    @Override
    public void run() {
        CloseableIterator<ChaincodeEvent> events = network.getChaincodeEvents("fabric-smart-contract");
        log.info("chaincodeEvents {} " , events);

        // events.hasNext() 會阻塞等待
        while (events.hasNext()) {
            ChaincodeEvent event = events.next();
            log.info("receive chaincode event {} , transaction id {} ,  block number {} , payload {} "
                    , event.getEventName() , event.getTransactionId() , event.getBlockNumber() , StringUtils.newStringUtf8(event.getPayload()));
        }
    }
}

# 在java應(yīng)用訪問智能合約
# git地址:https://gitee.com/baihu_shusheng/fabric-contract-api.git

六、Fabric2.4.6 prometheus & grafana 監(jiān)控網(wǎng)絡(luò) (ubuntu 22.04)

參考:
https://www.bilibili.com/video/BV1eS4y1L7Zo/?spm_id_from=333.788.recommend_more_video.2&vd_source=ef83736476a46166544cd38458b6b130

https://www.bilibili.com/video/BV1yR4y1G7fZ/?spm_id_from=333.337.search-card.all.click&vd_source=ef83736476a46166544cd38458b6b130

https://github.com/hyperledger/fabric-gateway-java/
https://github.com/hyperledger/fabric-gateway

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容