有人能帮我看下我这么用 PoolingHttpClientConnectionManager 是线程安全的吗? - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
hheedat
V2EX    Java

有人能帮我看下我这么用 PoolingHttpClientConnectionManager 是线程安全的吗?

  •  
  •   hheedat Sep 10, 2017 4437 views
    This topic created in 3151 days ago, the information mentioned may be changed or developed.

    没写过 Java,心里不顶真;我看了网上的资料应该 ok,试了下也没发现什么问题;要并发的去发送一些请求,用到了连接池,我这样应该是线程安全的吧?

    public class MyRequest { private static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(MyRequest.class); private final String REQUEST_URL; private ExecutorService executorService; private Queue<Map<String, String>> tasks; private static PoolingHttpClientConnectionManager cm; //<----- private static CloseableHttpClient httpClient; private MyRequest(int taskQueueSize, int executorCount, String requestRL, Map<String, Object> connConfig) { this.tasks = new ArrayBlockingQueue<>(taskQueueSize); this.executorService = Executors.newFixedThreadPool(executorCount); REQUEST_URL = requestURL; String proxyHost = connConfig.get("proxyHost").toString(); int proxyPort = Integer.parseInt(connConfig.get("proxyPort").toString()); cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(Integer.parseInt(connConfig.get("maxTotal").toString())); cm.setDefaultMaxPerRoute(Integer.parseInt(connConfig.get("defaultMaxPerRoute").toString())); RequestConfig cOnfig= RequestConfig.custom() .setConnectTimeout(Integer.parseInt(connConfig.get("connectTimeout").toString())) .setSocketTimeout(Integer.parseInt(connConfig.get("socketTimeout").toString())) .setConnectionRequestTimeout(Integer.parseInt(connConfig.get("cxxRxxTxout").toString())) .build(); HttpClientBuilder httpClientBuilder = HttpClients.custom() .setConnectionManager(cm) .setDefaultRequestConfig(config); if (!proxyHost.equals("") && 0 != proxyPort) { httpClient = httpClientBuilder.setProxy(new HttpHost(proxyHost, proxyPort)).build(); } else { httpClient = httpClientBuilder.build(); } } private void addTask(Map<String, String> parameters) { tasks.offer(parameters); } private void flush() { List<Future> futures = this.tasks.stream() .map(this::delegate) .collect(Collectors.toList()); futures.forEach((f) -> { try { f.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }); this.tasks.clear(); } private Future delegate(Map<String, String> parameters) { return this.executorService.submit(() -> { doRequest(parameters, REQUEST_URL); }); } private void doRequest(Map<String, String> parameters, String url) { CloseableHttpResponse resp = null; HttpGet get = null; try { URIBuilder builder = new URIBuilder(url); builder.addParameter("foo", parameters.get("bar")); get = new HttpGet(builder.build()); //<----- resp = httpClient.execute(get); //<----- if (resp.getStatusLine().getStatusCode() != 200) { LOGGER.warn("xxx"); } else { LOGGER.info("xxx"); } resp.close(); } catch (URISyntaxException e) { LOGGER.warn("xxx" + e.getMessage()); } catch (ClientProtocolException e) { LOGGER.warn("xxx" + e.getMessage()); } catch (IOException e) { LOGGER.warn("xxx" + e.getMessage()); } finally { if (resp != null) { try { resp.close(); } catch (IOException e) { e.printStackTrace(); } } } } private void shutdown() { this.executorService.shutdown(); } public static void main(String args[]) throws IOException { String logPath = System.getProperty("readLogPath"); String requestURL = System.getProperty("requestURL"); int taskQueueSize = Integer.valueOf(System.getProperty("max.requests", "2000")); int executorCount = Integer.valueOf(System.getProperty("num.executors", "100")); int interval = Integer.valueOf(System.getProperty("max.interval", "500")); String proxyHost = System.getProperty("proxyHost", ""); int proxyPort = Integer.parseInt(System.getProperty("proxyInt", "0")); int maxTotal = Integer.parseInt(System.getProperty("maxTotal", "5000")); int defaultMaxPerRoute = Integer.parseInt(System.getProperty("defaultMaxPerRoute", "1000")); int cOnnectTimeout= Integer.parseInt(System.getProperty("connectTimeout", "1000")); int socketTimeout = Integer.parseInt(System.getProperty("socketTimeout", "3000")); int cOnnectionRequestTimeout= Integer.parseInt(System.getProperty("connectionRequestTimeout", "3000")); Map<String, Object> cOnnConfig= new HashMap<>(); connConfig.put("proxyHost", proxyHost); connConfig.put("proxyPort", proxyPort); connConfig.put("maxTotal", maxTotal); connConfig.put("defaultMaxPerRoute", defaultMaxPerRoute); connConfig.put("connectTimeout", connectTimeout); connConfig.put("socketTimeout", socketTimeout); connConfig.put("connectionRequestTimeout", connectionRequestTimeout); try { MyRequest syncLog = new MyRequest(taskQueueSize, executorCount, requestURL, connConfig); Configuration cOnf= new Configuration(); FileSystem fs = FileSystem.get(conf); Path path = new Path(logPath); BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(path))); try { String line; int size = 0; long startTs = System.currentTimeMillis(); line = br.readLine(); while (line != null) { JsonElement root = new JsonParser().parse(line); Map<String, String> parameters = new HashMap<>(); JsonObject rootJson = root.getAsJsonObject(); for (Map.Entry entry : rootJson.entrySet()) { parameters.put(entry.getKey().toString(), rootJson.get(entry.getKey().toString()).getAsString()); } syncLog.addTask(parameters); ++size; if (size >= taskQueueSize || (System.currentTimeMillis() - startTs) > interval) { syncLog.flush(); size = 0; startTs = System.currentTimeMillis(); } line = br.readLine(); } if (0 != size) { syncLog.flush(); } } catch (IOException e) { LOGGER.error("xxx" + e.getMessage()); } finally { br.close(); } syncLog.shutdown(); } catch (Exception e) { e.printStackTrace(); } } } 
    2 replies    2017-09-11 07:56:27 +08:00
    Finest
        1
    Finest  
       Sep 11, 2017
    oRequest 的 resp.close()重复了吧,既然你都在 finally 里 close 了
    Finest
        2
    Finest  
       Sep 11, 2017   1
    还有就是 ArrayBlockingQueue 的用法有问题,你这用法还不如直接用 List 批量提交。
    如果想用到 Queue,那直接开 N 个线程作为消费者线程。
    About     Help     Advertise     Blog     API     FAQ     Solana     948 Online   Highest 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 39ms UTC 21:32 PVG 05:32 LAX 14:32 JFK 17:32
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86