我们先配置线程池,比较简单
下面是http连接池的配置
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
destroy-method="close">
import org.apache.http.conn.HttpClientConnectionManager;
/**
*
* 定期清理无效连接线程
*
*/
public class IdleConnectionEvictor extends Thread
{
/**
* 连接管理器
*/
private final HttpClientConnectionManager connectionManager;
/**
* 停止标志
*/
private volatile boolean shutdown;
/**
* 构造方法
*
* @param connectionManager
*/
public IdleConnectionEvictor(HttpClientConnectionManager connectionManager)
{
this.connectionManager = connectionManager;
// 启动线程
this.start();
}
@Override
public void run()
{
try
{
while (!shutdown)
{
synchronized (this)
{
// 每隔5秒执行检测关闭失效的连接
wait(5000);
// 关闭失效的连接
connectionManager.closeExpiredConnections();
}
}
}
catch (InterruptedException e)
{
// 结束
}
}
/**
*
* 停止方法
*
* @return void
*/
public void shutdown()
{
// 设置停止标志
shutdown = true;
synchronized (this)
{
notifyAll();
}
}
}
当然可以在进行封装成bean注入直接调用post,get
@Autowired
@Qualifier("taskExecutor")
private TaskExecutor taskExecutor;
@Autowired
@Qualifier("httpClient")
private HttpClient httpClient;
实例
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;
import com.bessky.financial.common.constant.SystemConstants;
import com.bessky.financial.pojo.pay.Pay;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
/**
*
* p卡供应商主体账号余额查询更新
*
* @author 罗平
* @version Bessky V100R001 2019年3月26日
* @since Bessky V100R001C00
*/
@JobHandler(value = "createPayoneerToken")
@Component
public class CreatePayoneerTokenJobHandler2 extends IJobHandler
{
@Autowired
@Qualifier("taskExecutor")
private TaskExecutor taskExecutor;
@Autowired
@Qualifier("httpClient")
private HttpClient httpClient;
private static final String URL = "https://www.baidu.com";
@Override
public ReturnT
{
Pay payQuery = new Pay();
payQuery.setStatus(SystemConstants.STATUS_TYPE_ACTIVE);
for (int i = 0; i < 100; i++)
{
taskExecutor.execute(new CreateToken(i));
}
return SUCCESS;
}
class CreateToken implements Runnable
{
private int num;
public CreateToken(int num)
{
this.num = num;
}
@Override
public void run()
{
HttpResponse response = null;
try
{
HttpGet httpGet = new HttpGet(URL);
response = httpClient.execute(httpGet);
String str = EntityUtils.toString(response.getEntity());
System.err.println("第" + num + "次:" + str);
}
catch (Exception e)
{
return;
}
}
}
}