【问题标题】:How to process/select/iterate based on random percentage value in the Spring Batch Processor?如何根据 Spring Batch Processor 中的随机百分比值处理/选择/迭代?
【发布时间】:2017-02-04 02:50:31
【问题描述】:

这是 Spring Batch 应用程序,读取器一次将 1 个对象传递给处理器。然而,可能有许多(数千个)对象被读取/处理。

在处理器中,仅根据传入的百分比随机选择值 - 这是一个整数值(小于 100)。

此百分比值是可配置的,并作为作业参数发送到 Batch 应用程序。 它可以是任何 10%、20%、25%、30%、50%、75% 等等。

例如,如果它是 50%,那么处理器接收到的 2 个对象中只有 1 个会被处理,而另一个将被忽略(返回 null)。 如果是 75%,那么处理器接收到的 4 个对象中有 3 个将被处理,1 个将被忽略。

我在想这样的事情

    int current = 0;

public <T> process(<T> item) {

    JobParameters parameters = stepExecution.getJobParameters();
    int randomPercent = parameters.getString("percentage");
    // randomPercent = 50;

    int num = 100/randomPercent;  
    // num = 100/50 = 2

    if(current % n == 0) {
       // process this object
       current++;
       return item;

    } else {
        // do not process this
        current++;
        return null;
    }
}

上述代码在 randomPercent 大于 50% 的情况下不起作用。

有没有更好/优雅的方法来处理百分比值并基于它进行迭代。

谢谢!

【问题讨论】:

  • 我有 2 个问题。你有最小数量的对象吗?作者是做什么的?
  • 1.至少可能有几百个项目/对象 2. 基于 randomPercent 值,如果项目由处理器处理,则将其发送给 writer,writer 发送通知,如果项目未处理,处理器将 null 返回给 writer - 无发生。

标签: java loops iteration spring-batch


【解决方案1】:

根据您的意见,我正在考虑以下方法。

处理器将有一个队列来处理。如果队列已满 100,我们将开始按百分比提取项目并将列表发送给 Writer。否则,处理器将继续将项目填充到队列中。

代码为:

@Value("#{jobParameters['percentage']}")
private Integer percentage;

private List queue = new ArrayList();
private Integer count = 0;

public List<<T>> process(<T> item) {
        count ++;

        if (count == 100) {
            List result = pickupItemByPercentage();
            this.count = 0;     // reset
            this.queue.clear(); // reset;

            return result;
        }
        else {
            this.queue.add(item);
            return null;
        }
}

/**
 This method is to return a list of item base on the percentage
**/
private List pickupItemByPercentage() {
    List result = new ArrayList();

    // TODO: you can change the logic to pick up items if you want.
    for (int i=0; i<this.percentage; i++) {
        result.add(this.queue.get(i));
    }

    return result;
}

【讨论】:

    猜你喜欢
    • 2016-02-26
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 2016-09-10
    相关资源
    最近更新 更多