Spring + HttpClient配置多线程

HttpClient通过MultiThreadedHttpConnectionManager实现多线程通讯

HttpConnectionManagerParams设置connectionTimeout链接超时,soTimeout读取数据超时,maxTotalConnections,defaultMaxConnectionsPerHost等等参数

MultiThreadedHttpConnectionManager多线程中属性params是HttpConnectionManagerParams

xml配置:

<?xml version="1.0" encoding="UTF-8"?>    
<beans xmlns="http://www.springframework.org/schema/beans"    
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
    xmlns:aop="http://www.springframework.org/schema/aop"    
    xmlns:tx="http://www.springframework.org/schema/tx"    
    xsi:schemaLocation="     
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd     
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd     
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">    
    
    <!-- httpclient线程池 -->    
    <bean id="connectionManagerParams" class="org.apache.commons.httpclient.params.HttpConnectionManagerParams">    
        <property name="connectionTimeout" value="10000"/>    
        <property name="soTimeout" value="10000"/>    
        <property name="maxTotalConnections" value="30"/>    
        <property name="defaultMaxConnectionsPerHost" value="20"/>    
    </bean>      
         
    <bean id="connectionManager" class="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager">    
        <property name="params" ref="connectionManagerParams"/>    
    </bean>    
         
    <bean id="httpclient" class="org.apache.commons.httpclient.HttpClient">    
        <constructor-arg>    
            <ref bean="connectionManager"/>    
        </constructor-arg>    
    </bean>    
         
    <bean id="httpClientUtil" class="com.chinaums.utils.HttpClientUtil">    
        <property name="httpclient" ref="httpclient"/>    
    </bean>    
         
         
</beans> 

java config配置:

package com.httpclient.config;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class HttpConfig {

	@Bean
	public HttpConnectionManagerParams connectionManagerParams() {
		HttpConnectionManagerParams param = new HttpConnectionManagerParams();
		param.setConnectionTimeout(10000);
		param.setSoTimeout(10000);
		param.setMaxTotalConnections(30);
		param.setDefaultMaxConnectionsPerHost(20);
		return param;
	}
	
	@Bean
	public MultiThreadedHttpConnectionManager connectionManager(HttpConnectionManagerParams param) {
		MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
		connectionManager.setParams(param);
		return connectionManager;
	}
	
	@Bean
	public HttpClient httpClient(MultiThreadedHttpConnectionManager connectionManager) {
		return new HttpClient(connectionManager);
	}
}

工具类:

package com.httpclient.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.factory.annotation.Autowired;  
  
  
/** 
 * httpClient工具类 
 *  
 
 *  
 */  
public class HttpClientUtil {  
  
	@Autowired
    private  HttpClient httpclient;  
  
    /** 
     * 以get方式发送http请求 
     *  
     * @param url 
     * @return 
     */  
    public String sendRequest(String url) {  
        GetMethod getMethod = new GetMethod(url);  
        try {  
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());  
//          httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(6000);  
//          getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,6000);  
            httpclient.executeMethod(getMethod);  
            return getMethod.getResponseBodyAsString();  
        } catch (Exception e) {  
            e.printStackTrace();  
            return "FAIL";  
        }  
        finally{  
            getMethod.releaseConnection();  
        }  
    }  
      
    /** 
     * 以get方式发送http请求 
     *  
     * @param url 
     * @return 
     */  
    public boolean isActive(String url) {  
        boolean flag = false;  
        GetMethod getMethod = new GetMethod(url);  
        try {  
            getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());  
            int statusCode = httpclient.executeMethod(getMethod);  
            if(statusCode==200){  
                flag = true;  
            }  
            return flag;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return flag;  
        }  
        finally{  
            getMethod.releaseConnection();  
        }  
    }  
      
    /** 
     * 以post方式发送http请求 
     *  
     * @param url 
     * @return 
     */  
    public  int sendRequestAsPost(String url) {  
        PostMethod postMethod = new PostMethod(url);  
        try {  
            postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());  
            httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(1000);  
            postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,1000);  
  
            int statusCode = httpclient.executeMethod(postMethod);  
            return statusCode;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return 500;  
        }  
        finally{  
            postMethod.releaseConnection();  
        }  
    }  
  
    /** 
     * 验证请求是否是本机发出 
     *  
     * @param request 
     *            true本机发出 false非本机发出 
     * @return 
     */  
    public static boolean isRequestFromSelf(HttpServletRequest request) {  
        if (getRemoteIpAddr(request).equals(getLocalIpAddr()))  
            return true;  
        else  
            return false;  
    }  
  
    /** 
     * 获取远程客户端IP地址 
     *  
     * @param request 
     * @return 
     */  
    public static String getRemoteIpAddr(HttpServletRequest request) {  
        String ip = request.getHeader("X-Forwarded-For");  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))  
            ip = request.getHeader("Proxy-Client-IP");  
  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))  
            ip = request.getHeader("WL-Proxy-Client-IP");  
  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))  
            ip = request.getHeader("HTTP_CLIENT_IP");  
  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))  
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
  
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))  
            ip = request.getRemoteAddr();  
  
        if ("0:0:0:0:0:0:0:1".equals(ip.trim()))  
            ip = "server";  
  
        // 判断请求是否是本机发出,如果是本机发出,那么就获取本机地址  
        if ("127.0.0.1".equals(ip) || ip.equalsIgnoreCase("localhost"))  
            ip = getLocalIpAddr();  
  
        return ip;  
    }  
  
    /** 
     * 获取本机IP地址 
     *  
     * @return 
     */  
    public static String getLocalIpAddr() {  
        try {  
            Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();  
            InetAddress ip = null;  
            String ipAddr = null;  
            while (netInterfaces.hasMoreElements()) {  
                NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();  
                ip = (InetAddress) ni.getInetAddresses().nextElement();  
                if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {  
                    ipAddr = ip.getHostAddress();  
                    break;  
                }  
            }  
            return ipAddr;  
        } catch (SocketException e) {  
            e.printStackTrace();  
            return null;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  
  
    /** 
     * 判断某回调地址是否是指定的网关地址 
     *  
     * @param notifyUrl 
     * @param getwayList 
     * @return true 是网关 false不是网关地址 
     */  
    public static boolean isLocalNotifyUrl(String notifyUrl, List getwayList) {  
        boolean flag = false;  
        for (Object object : getwayList) {  
            String getway = (String) object;  
            if (notifyUrl.toLowerCase().contains(getway)) {  
                flag = true;  
                break;  
            }  
        }  
        return flag;  
    }  
      
    public static void main(String[] arg){  
        HttpClient httpclient = new HttpClient();  
        String url = "http://www.163.com";  
        GetMethod method = new GetMethod(url);  
        try {  
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());  
            int statusCode = httpclient.executeMethod(method);  
            System.out.println(statusCode);  
            byte[] responseBody = method.getResponseBody();  
            System.out.println(new String(responseBody));  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        finally{  
            method.releaseConnection();  
        }  
      
          
    }  

}

猜你喜欢

转载自blog.csdn.net/liu911025/article/details/80837765
今日推荐