需求中的轴突4快照

问题描述

我使用spring boot和axon示例,我实现了快照功能,下面的代码运行良好,在3个事件之后,我在数据库的表snapshot_event_entry中找到了数据

@Configuration
@AutoConfigureAfter(value = { AxonAutoConfiguration.class })
public class AxonConfig {

    @Bean
    public SnapshottriggerDeFinition catalogSnapshottrigger(Snapshotter snapshotter) {
        return new EventCountSnapshottriggerDeFinition(snapshotter,3);
    }
}


@Aggregate(snapshottriggerDeFinition = "catalogSnapshottrigger")
public class CatalogAggregate { }

我的问题是,有没有一种方法可以按需制作快照?这意味着我想实现一个API来做快照,而不是在3个事件发生后自动

解决方法

没有任何东西。 实现您需要的一种方法是创建一个专用命令,例如PerformShapshotCmd,它将携带AggregationId信息和一个@CommandHandler到您的Aggregate中。然后,您可以让Spring自动连接Snapshotter实例bean,并调用scheduleSnapshot(Class<?> aggregateType,String aggregateIdentifier)方法。

下面一些可以指导您的代码段。

data class PerformShapshotCmd(@TargetAggregateIdentifier val id: String)
    @CommandHandler
    public void handle(PerformShapshotCmd cmd,Snapshotter snapshotter) {
        logger.debug("handling {}",cmd);

        snapshotter.scheduleSnapshot(this.getClass(),cmd.getId());
    }

您还应该在配置中定义一个Snapshotter类型的Bean

@Bean
public SpringAggregateSnapshotterFactoryBean snapshotter() {
    SpringAggregateSnapshotterFactoryBean springAggregateSnapshotterFactoryBean = new SpringAggregateSnapshotterFactoryBean();
    //Setting async executors
    springAggregateSnapshotterFactoryBean.setExecutor(Executors.newSingleThreadExecutor());
    return springAggregateSnapshotterFactoryBean;
}

请注意,您的commandHandler的第一个参数必须是命令,否则框架将在启动时抱怨异常。