【发布时间】: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