【问题标题】:Block a partcular machine for a particular period of time interval在特定的时间间隔内阻止特定的机器
【发布时间】:2016-05-15 23:23:56
【问题描述】:

我正在开发一个库,我在其中对我的服务进行 Http 调用,如果我的服务机器没有响应(有套接字超时或连接超时),我将它们添加到我的本地 blockList 并且如果机器被屏蔽了 5 次,然后我就不给他们打电话了。

假设machineA 没有响应(throwing RestClientException),我将每次调用onFailure 方法并继续递增计数器,然后在再次调用machineA 时,我通过传递@ 检查isBlocked 方法987654327@ 作为主机名,5 作为阈值,所以如果machineA 已被阻止 5 次,那么我根本不会打电话给他们。我的库是多线程的,这就是我在这里使用 volatile 的原因,因为我希望所有线程都看到相同的值。

以下是我在DataMapping 类中的内容:

public static volatile ConcurrentHashMap<String, AtomicInteger> blockedHosts =
      new ConcurrentHashMap<String, AtomicInteger>();

boolean isBlocked(String hostname, int threshold) {
    AtomicInteger count = blockedHosts.get(hostname);
    return count != null && count.get() >= threshold;
}

void onFailure(String hostname) {
    AtomicInteger newValue = new AtomicInteger();
    AtomicInteger val = blockedHosts.putIfAbsent(hostname, newValue);
    // no need to care about over-reaching 5 here
    (val == null ? newValue : val).incrementAndGet();
}

void onSuccess(String hostname) {
    blockedHosts.remove(hostname);
}

问题陈述:-

现在我想再添加一项功能,即 - 如果 machineA 被阻塞(因为它的阻塞计数 >= 5),那么我想让它阻塞 x 间隔。我将有另一个参数(key.getInterval()),它将告诉我们我希望这台机器阻塞多长时间,并且在该间隔过去之后,只有我会开始打电话给他们。我无法理解如何添加此功能?

下面是我的主线程代码,我在其中使用DataMapping 方法检查主机名是否被阻止以及阻止主机名。

@Override
public DataResponse call() {
    ResponseEntity<String> response = null;

    List<String> hostnames = some_code_here;

    for (String hostname : hostnames) {
        // If hostname is in block list, skip sending request to this host
        if (DataMapping.isBlocked(hostname)) {
            continue;
        }
        try {
            String url = createURL(hostname);
            response = restTemplate.exchange(url, HttpMethod.GET, key.getEntity(), String.class);
            DataMapping.onSuccess(hostname);

            // some code here to return the response if successful
        } catch (RestClientException ex) {
            // adding to block list
            DataMapping.onFailure(hostname);
        }
    }

    return new DataResponse(DataErrorEnum.SERVER_UNAVAILABLE, DataStatusEnum.ERROR);        
}

我怎样才能在特定的时间段内阻止特定的机器,并且一旦该时间间隔过去,然后才开始调用它们?

【问题讨论】:

  • 您需要跟踪它何时被阻塞,以判断间隔是否已过,而不仅仅是它是否被阻塞。

标签: java multithreading guava atomic google-guava-cache


【解决方案1】:

您可以使用ScheduledExecutorServiceschedule 在一定超时后重置计数器。

您可以在 DataMapping 类中声明它:

private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); // or perhaps the thread pool version ?

在您的 onFailure() 方法中,您可以决定是要重置还是在某个超时后递减计数器:

void onFailure(String hostname) {
    // you can use `computeIfAbsent` in java8
    AtomicInteger val = blockedHosts.computeIfAbsent(hostname, key -> new AtomicInteger());
    int count = val.incrementAndGet();
    // the test here is `==` to make sure the task is scheduled only once
    if (count == threshold) {
        scheduler.schedule(() -> blockedHosts.remove(hostname), 5L, TimeUnit.MINUTES);  // or you may choose to just decrement the counter
    }
}

作为旁注,没有理由制作blockedHosts volatile。该参考永远不会改变;它应该是final;可能是private


在 java7 中,上面的代码如下所示:

void onFailure(String hostname) {
    AtomicInteger newValue = new AtomicInteger();
    AtomicInteger val = blockedHosts.putIfAbsent(hostname, newValue);
    int count = (val == null ? newValue : val).incrementAndGet();
    // the test here is `==` to make sure the task is scheduled only once
    if (count == threshold) {
        scheduler.schedule(new Runnable() {
            @Override public void run() {
                blockedHosts.remove(hostname);  // or you may choose to just decrement the counter
            }
        }, 5L, TimeUnit.MINUTES);
    }
}

【讨论】:

  • 不幸的是,我还在使用 Java 7,但无法迁移到 Java 8。Java 7 会是什么样子?
  • 几乎相同,除了 computeIfAbsent 和简洁的 lambda 语法。您必须实例化一个Callable(或Runnable)并将其提交给执行器服务。
  • 你能不能用 Java 7 的建议来更新它。我仍在尝试了解上述代码的作用。一旦我在 Java 7 中看到,我将有几个问题,以确保我理解。
  • 完成。我希望它编译:)
  • 是的,我认为它肯定会编译。我们已经对5 分钟窗口进行了硬编码,所以如果我传入该方法,那么它也应该可以正常工作吗?
猜你喜欢
  • 1970-01-01
  • 2011-02-25
  • 2015-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多