在 Corda 中,如何从服务启动流?

In Corda, how to start a flow from a service?

我在我的节点上创建了一个 CordaService 运行。我希望此服务根据各种条件启动流程。但是,提供给服务的ServiceHub不提供启动流的能力。

是否有服务启动流量的流量?我该怎么做?

是的。只需在其构造函数中传递 CordaService 一个 AppServiceHub 而不是 ServiceHub

AppServiceHub 接口扩展了 ServiceHub 接口以赋予节点启动流的能力:

interface AppServiceHub : ServiceHub {

    fun <T> startFlow(flow: FlowLogic<T>): FlowHandle<T>

    fun <T> startTrackedFlow(flow: FlowLogic<T>): FlowProgressHandle<T>
}

是,将 AppServiceHub 传递给构造函数

在科特林中:

class MyCordaService(private val serviceHub: AppServiceHub) : SingletonSerializeAsToken() {

    init {
        // code ran at service creation / node startup
    }

    // public api of service
}

或Java:

public class MyCordaService extends SingletonSerializeAsToken {

    private AppServiceHub serviceHub;

    public MyCordaService(AppServiceHub serviceHub) {
        this.serviceHub = serviceHub;
        // code ran at service creation / node startup
    }

    // public api of service
}

重要:为了避免 运行 节点之间可能出现的任何潜在死锁,从它们自己的 线程

例如:

public class MyCordaService extends SingletonSerializeAsToken {

    private AppServiceHub serviceHub;

    public MyCordaService(AppServiceHub serviceHub) {
        this.serviceHub = serviceHub;
        // code ran at service creation / node startup
    }

    // public api of service
   public void doSomething(){   
    // do something and start a new flow
    Thread flowThread = new Thread(new StartFlow());
    flowThread.start();
   }

   private class StartFlow implements Runnable {
     @Override
        public void run() {
         // start new flow
         CordaFuture<SignedTransaction> cordaFuture=  appServiceHub.startFlow(new 
         Flow(params).getReturnValue();

         SignedTransaction signedTransaction = cordaFuture.get();
        }
   }
}