首页 > 解决方案 > 跟踪发布到事件中心并存储在执行上下文中的项目计数

问题描述

我在一个常见的 maven 项目中有一个接口,有两个发布方法都返回布尔值:

public interface IPublisher<T, U> {    
    boolean publish(Context ctx, T model);    
    boolean publish(Context ctx, List<? extends ModelHolder> model);    
}

我有这个接口的一个实现:

public class Publisher implements IPublisher<PriceHolder, JSONObject> {

    private final DataPublisher dataPublisher;

    public Publisher(final DataPublisher dataPublisher) {
        this.dataPublisher = dataPublisher;
    }

    @Override
    public boolean publish(Context context, PriceHolder priceHolder) {
    
        if (isInvalid(priceHolder)) {
            return false;
        }

        try {
            dataPublisher.publish(data);

        } catch (ConnectionException | DataBuilderException ex) {
            String message = "someMessage";
            LOGGER.error(message, ex);
        } catch (TimeoutException e) {
            LOGGER.error(message, e);
        }

        return true;
    }

    @Override
    public boolean publish(Context ctx, List<? extends ModelHolder> list) {
        if (list == null) {
            return false;
        }

        for (ModelHolder item : list) {
            publish(ctx, (PriceHolder) item);
        }

        return true;
    }

    private boolean isInvalid(PriceHolder priceHolder) {
    }
}

目前,这个实现没有记录有多少已经发布,这是我需要传递给正在调用的客户端的publish()

客户端实例化一个 Publisher 类的 Spring Bean:

@Bean
public IPublisher publisher(DataItemPublisher dataItemPublisher) {
    return new Publisher(dataItemPublisher);
}

客户端应用程序正在使用 Spring Batch,它在工作流配置类中发布如下:

@Bean
@Scope(value = "step", proxyMode = ScopedProxyMode.INTERFACES)
public ItemWriter<PriceHolder> publish(@Value("#{jobExecutionContext['MY_CONTEXT']}") Context ctx) {
    return items -> {
        publisher.publish(ctx, items);
    };
}

publisherIPublisher 实例在哪里。这些项目是按块处理的,在处理结束时,我需要一个已发布数量的汇总计数,但我不确定如何实现这一点,因为 publish() 返回布尔值。我想获得总发布计数,然后我可以将它保存在 executionContext 中。这样我就可以在工作流程的后续步骤中使用此计数进行报告。例如收到与发布的计数。我怎样才能做到这一点?

标签: javaspringdesign-patternsspring-batch

解决方案


目前,此实现不记录已发布的数量,这是我需要传递给调用 publish() 的客户端的内容。

由于此实现不提供让客户端知道发布了多少项目的方法,并且既然您说过The client app is using spring batch,您将无法获取该信息并将其存储在 Spring Batch 的执行上下文中。您需要修复您的界面并使其返回比布尔值更丰富的类型。


推荐阅读