SDK-Java跑通fabric2.2自带的fabcar,简单实现

首先,确保你的网络可以跑通,然后进去fabcar目录下

./startFabric.sh 

启动成功后,

 

可以看到这样的页面,

(你也可以cd go然后go run fabcar.go用自带的go-sdk在终端看)

然后,回到上一级目录的test-network里

把ordererOraganizations和peerOrganizations复制到你IDEA的resource目录下,

先看看IDEA的目录

HyperledgerFabricAppJavaDemoApplication:springboot的启动类
package com.example;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;


@SpringBootApplication
@EnableConfigurationProperties
public class HyperledgerFabricAppJavaDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(HyperledgerFabricAppJavaDemoApplication.class, args);

    }

}

 

 

HyperLedgerFabricGatewayJavaConfig:用GatewayJava来连接
package com.example;

import io.grpc.ManagedChannel;
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hyperledger.fabric.gateway.*;
import org.hyperledger.fabric.sdk.BlockEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Properties;

/**
 * @author he peng
 * @date 2022/3/3
 */

@Configuration
@AllArgsConstructor
@Slf4j
public class HyperLedgerFabricGatewayJavaConfig {


    @Bean
    public Gateway gateway() throws Exception {
        Properties properties = new Properties();
        InputStream inputStream = SdkDemo2.class.getResourceAsStream("/fabric.config.properties");
        properties.load(inputStream);

        String networkConfigPath = properties.getProperty("networkConfigPath");
        String certificatePath = properties.getProperty("certificatePath");
        X509Certificate certificate = readX509Certificate(Paths.get(certificatePath));
        String privateKeyPath = properties.getProperty("privateKeyPath");
        PrivateKey privateKey = getPrivateKey(Paths.get(privateKeyPath));
        Wallet wallet = Wallets.newInMemoryWallet();
        wallet.put("user1", Identities.newX509Identity("Org2MSP",certificate,privateKey));

        Gateway.Builder builder = Gateway.createBuilder()
                .identity(wallet , "user1")
                .networkConfig(Paths.get(networkConfigPath));

        Gateway gateway = builder.connect();

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

        return gateway;
    }



    @Bean
    public Contract fabcar(Gateway gateway) {

        Network network = gateway.getNetwork("mychannel");

        Contract contract = network.getContract("fabcar");
        return contract;
    }

    private static X509Certificate readX509Certificate(final Path certificatePath) throws IOException, CertificateException {
        try (Reader certificateReader = Files.newBufferedReader(certificatePath, StandardCharsets.UTF_8)) {
            return Identities.readX509Certificate(certificateReader);
        }
    }

    private static PrivateKey getPrivateKey(final Path privateKeyPath) throws IOException, InvalidKeyException {
        try (Reader privateKeyReader = Files.newBufferedReader(privateKeyPath, StandardCharsets.UTF_8)) {
            return Identities.readPrivateKey(privateKeyReader);
        }
    }
}
FabcarController:
package com.example;



import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.StringUtils;
import org.hyperledger.fabric.gateway.Contract;
import org.hyperledger.fabric.gateway.Gateway;
import org.hyperledger.fabric.gateway.GatewayException;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/car")
@Slf4j
@AllArgsConstructor
public class FabcarController {


    final Gateway gateway;

    final Contract contract;





    @GetMapping("/{key}")
    public Map<String, Object> queryCatByKey(@PathVariable String key) throws GatewayException{

        Map<String, Object> result = Maps.newConcurrentMap();
        byte[] queryAssets = contract.evaluateTransaction("QueryCar",key);

        result.put("payload", StringUtils.newStringUtf8(queryAssets));
        result.put("status", "ok");

        return result;


    }

    @GetMapping("/all")
    public Map<String, Object> queryAllCatByKey() throws GatewayException{

        Map<String, Object> result = Maps.newConcurrentMap();
        byte[] queryAllAssets = contract.evaluateTransaction("QueryAllCars");

        result.put("payload", StringUtils.newStringUtf8(queryAllAssets));
        result.put("status", "ok");

        return result;
    }
    
}

剩下就是resource里的内容了:

{
  "name": "basic-network",
  "version": "1.0.0",
  "dependencies": {
  },
  "client": {
    "organization": "Org1",
    "connection": {
      "timeout": {
        "peer": {
          "endorser": "300"
        },
        "orderer": "300"
      }
    }
  },
  "channels": {
    "mychannel": {
      "orderers": [
        "orderer.example.com"
      ],
      "peers": {
        "peer0.org1.example.com": {
          "endorsingPeer": true,
          "chaincodeQuery": true,
          "ledgerQuery": true,
          "eventSource": true
        },
        "peer0.org2.example.com": {
          "endorsingPeer": true,
          "chaincodeQuery": true,
          "ledgerQuery": true,
          "eventSource": true
        }
      }
    }
  },
  "organizations": {
    "Org1": {
      "mspid": "Org1MSP",
      "peers": [
        "peer0.org1.example.com"
      ],
      "certificateAuthorities": [
        "ca-org1"
      ],
      "adminPrivateKeyPEM": {
        "path": "src/main/resources/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore/c838e33842b9a2f9a45a9bd9d7e6263e68cac66c3a25007ea44ee8f97310cc85_sk"
      },
      "signedCertPEM": {
        "path": "src/main/resources/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts/cert.pem"
      }
    },
    "Org2": {
      "mspid": "Org2MSP",
      "peers": [
        "peer0.org2.example.com"
      ],
      "certificateAuthorities": [
        "ca-org2"
      ],
      "adminPrivateKeyPEM": {
        "path": "src/main/resources/crypto-config/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp/keystore/120204af355e05c631b702212437fe5b144c611e09bc5867b26811be9320bb6d_sk"
      },
      "signedCertPEM": {
        "path": "src/main/resources/crypto-config/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp/signcerts/cert.pem"
      }
    }
  },
  "orderers": {
    "orderer.example.com": {
      "url": "grpcs://192.168.219.130:7050",
      "mspid": "OrdererMSP",
      "grpcOptions": {
        "ssl-target-name-override": "orderer.example.com",
        "hostnameOverride": "orderer.example.com"
      },
      "tlsCACerts": {
        "path": "src/main/resources/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/ca.crt"
      },
      "adminPrivateKeyPEM": {
        "path": "src/main/resources/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/keystore/c838e33842b9a2f9a45a9bd9d7e6263e68cac66c3a25007ea44ee8f97310cc85_sk"
      },
      "signedCertPEM": {
        "path": "src/main/resources/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/signcerts/cert.pem"
      }
    }
  },
  "peers": {
    "peer0.org1.example.com": {
      "url": "grpcs://192.168.219.130:7051",
      "grpcOptions": {
        "ssl-target-name-override": "peer0.org1.example.com",
        "hostnameOverride": "peer0.org1.example.com",
        "request-timeout": 120001
      },
      "tlsCACerts": {
        "path": "src/main/resources/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt"
      }
    },
    "peer0.org2.example.com": {
      "url": "grpcs://192.168.219.130:9051",
      "grpcOptions": {
        "ssl-target-name-override": "peer0.org2.example.com",
        "hostnameOverride": "peer0.org2.example.com",
        "request-timeout": 120001
      },
      "tlsCACerts": {
        "path": "src/main/resources/crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt"
      }
    }
  },
  "certificateAuthorities": {
    "ca-org1": {
      "url": "https://192.168.219.130:7054",
      "grpcOptions": {
        "verify": true
      },
      "tlsCACerts": {
        "path": "src/main/resources/crypto-config/peerOrganizations/org1.example.com/ca/ca.org1.example.com-cert.pem"
      },
      "registrar": [
        {
          "enrollId": "admin",
          "enrollSecret": "adminpw"
        }
      ]
    },
    "ca-org2": {
      "url": "https://192.168.219.130:8054",
      "grpcOptions": {
        "verify": true
      },
      "tlsCACerts": {
        "path": "src/main/resources/crypto-config/peerOrganizations/org2.example.com/ca/ca.org2.example.com-cert.pem"
      },
      "registrar": [
        {
          "enrollId": "admin",
          "enrollSecret": "adminpw"
        }
      ]
    }
  }
}

需要把所有节点的ip换成你自己虚拟机的ip(还有主机映射,参考我上一篇文章)

 把上面说的虚拟机里生成的这两个文件夹复制到你的IDEA中这文件夹的位置

fabric.config.properties,我这里用的是org2的证书来连接的

# 网络配置文件路径
networkConfigPath = src/main/resources/connection.json
# 用户1,机构2证书路径
certificatePath = src/main/resources/crypto-config/peerOrganizations/org2.example.com/msp/signcerts/cert.pem
# 用户1,机构2证书私钥路径
privateKeyPath = src/main/resources/crypto-config/peerOrganizations/org2.example.com/msp/keystore/ecbf251bbd8f962b385f08693260386c4c0134ad296d6ec6719f28956f803fdc_sk


# 通道名字
channelName = mychannel

# 链码名字
contractName = fabcar

pom.xml文件中加上依赖

<dependency>
    <groupId>org.hyperledger.fabric-sdk-java</groupId>
    <artifactId>fabric-sdk-java</artifactId>
    <version>1.4.7</version>
</dependency>

<dependency>
    <groupId>org.hyperledger.fabric</groupId>
    <artifactId>fabric-gateway-java</artifactId>
    <version>2.2.0</version>
</dependency>

最后,我们用postman跑一下 :

查单个数据 

查所有数据

 增加一条数据:

然后再查询所有数据:

 

 数据增加了,

再进行更改owner

 我们再查询CAR15的owner:

到此,fabric自带的fabcar链码的所有函数我们都通过SDK调用了。 

  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值