1

我正在尝试使用 fabric-sdk-go 制作一个简单的演示。我想知道为什么下面的代码(“client.Query”)返回错误“无法创建事务:Channel_Cfg_Cache - 缓存已关闭”?


func initSdkClient() (*channel.Client){
    sdk, err := fabsdk.New(config.FromFile("config.yaml"))
    if err != nil {
        logger.Fatalf("Failed to create new SDK: %s", err)
    }
    defer sdk.Close()

    //prepare channel client context using client context
    clientChannelContext := sdk.ChannelContext(channelID, fabsdk.WithUser("User1"), fabsdk.WithOrg(orgName))
    // Channel client is used to query and execute transactions (Org1 is default org)
    client, err := channel.New(clientChannelContext)
    if err != nil {
        logger.Fatalf("Failed to create new channel client: %s", err)
    }
    return client
}

func queryCC(client *channel.Client, targetEndpoints ...string) []byte {
    response, err := client.Query(channel.Request{ChaincodeID: ccID, Fcn: "invoke", Args: defaultQueryArgs},
        channel.WithRetry(retry.DefaultChannelOpts),
        channel.WithTargetEndpoints(targetEndpoints...),
    )
    if err != nil {
        ***logger.Fatalf("Failed to query funds: %s", err)*** // error: failed to create transactor: Channel_Cfg_Cache - cache is closed
    }
    return response.Payload
}

func main() {
    client := initSdkClient()

    existingValue := queryCC(client)
    logger.Info(existingValue)


    logger.Info("hello, world\n")
}
4

1 回答 1

1

可能是因为您在initSdkClient函数结束时关闭了 SDK 实例。main而是在函数结束时关闭 SDK 。

做类似的事情

type Setup struct {
    sdk    *fabsdk.FabricSDK
    client *channel.Client
}

func (setup *Setup) initSdkClient() *channel.Client {
    sdk, err := fabsdk.New(config.FromFile("config.yaml"))
    if err != nil {
        fmt.Errorf("Failed to create new SDK: %s", err)
    }
    setup.sdk = sdk
    //prepare channel client context using client context
    clientChannelContext := setup.sdk.ChannelContext(channelID, fabsdk.WithUser("User1"), fabsdk.WithOrg(orgName))
    // Channel client is used to query and execute transactions (Org1 is default org)
    client, err := channel.New(clientChannelContext)
    if err != nil {
        fmt.Errorf("Failed to create new channel client: %s", err)
    }
    setup.client = client
    return client
}

func (setup *Setup) queryCC(client *channel.Client, targetEndpoints ...string) []byte {
    response, err := setup.client.Query(channel.Request{ChaincodeID: ccID, Fcn: "invoke", Args: defaultQueryArgs},
        channel.WithRetry(retry.DefaultChannelOpts),
        channel.WithTargetEndpoints(targetEndpoints...),
    )
    if err != nil {
        fmt.Errorf("Failed to query funds: %s", err)
    }
    return response.Payload
}

func main() {
    var setup Setup
    client := setup.initSdkClient()
    defer setup.sdk.Close()

    existingValue := setup.queryCC(client)

}
于 2019-02-18T10:06:18.963 回答