gpt4 book ai didi

java - 如何在多线程环境下实现FIFO队列

转载 作者:行者123 更新时间:2023-12-01 16:25:22 24 4
gpt4 key购买 nike

我正在尝试为一个类实现一个队列,用于获取 URL 的 OpenGraph 数据。这个想法是,如果请求需要“代理”服务,则 OpenGraphIO 服务一次只允许一个请求。为了消除服务中的“同时代理请求”错误,我想在名为 OpenGraphFetcherImpl 的服务类内实现一个请求队列。但是,我不知道如何在 fetch() 方法内实现实际的队列本身。显然,fetch()方法可以在多线程环境中调用。

我的类外壳如下:

public class OpenGraphFetcherImpl implements OpenGraphFetcher {

private static final String[] domainsThatRequireProxy = {"instagram.com","facebook.com"};

private static final LinkedList<URL> proxyQueue = new LinkedList<>();

private final String api_key;

public OpenGraphFetcherImpl(String api_key) {
this.api_key = api_key;
}

/**
* Fetch OpenGraph information for a url. If the url is invalid or no data is returned, the OpenGraph
* object will be "empty" (non-null)
*
* Only one "proxy" request can be made at a time. Should a proxy be needed, the request will be queued
* and returned once previous requests have been completed.
*
* @param url end point to fetch OpenGraph data
* @return OpenGraph object
*/
@Override
@Nonnull
public OpenGraph fetch(URL url) {
if (useProxy(url)) {
// Clearly this code doesn't work, but logic should be to add the request to the queue and then make requests in FIFO order
proxyQueue.add(url);
return OpenGraphIO.fetchOpenGraphInfo(api_key, proxyQueue.poll(), true);
} else {
return OpenGraphIO.fetchOpenGraphInfo(api_key, url, false);
}
}

/**
* @param url url to test
* @return true if the host of the url matches any domains that require use of a proxy
*/
private boolean useProxy(URL url) {
return Arrays.stream(domainsThatRequireProxy).parallel().anyMatch(url.getHost()::contains);
}
}

最佳答案

根据您的描述,您希望在 useProxy 为 true 时限制对 fetch() 的同步调用。然后,您可以使用对象仅同步该情况:

public class OpenGraphFetcherImpl implements OpenGraphFetcher {
private static final Object fetchLock=new Object();

public OpenGraph fetch(URL url) {
if (useProxy(url)) {
synchronized(fetchLock) {
return OpenGraphIO.fetchOpenGraphInfo(api_key, url, true);
}
} else {
return OpenGraphIO.fetchOpenGraphInfo(api_key, url, false);
}
}
...

关于java - 如何在多线程环境下实现FIFO队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62158322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com