简单线程测试类

package com.zichen.xhkq.controller.storeXhPay;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zichen.xhkq.dao.order.StoreOrder;
import com.zichen.xhkq.pojo.order.Order;
import com.zichen.xhkq.service.MyThreadPoolManager;

@Controller
@RequestMapping("/test")
public class TestMy {

	private static final Logger log = LoggerFactory.getLogger(TestMy.class);

	@Resource
	StoreOrder storeOrder;

	@RequestMapping("/add")
	@ResponseBody
	public String add() throws Exception {
		for (int i = 0; i < 10; i++) {

			Order order = new Order();
			// orderNumber`,`storeId`,`storeName`,
			// `payStatus`,`openId`,`totalMoney`,`remark`,`tableId`
			order.setOrderNumber("2019031011230824" + i);
			order.setStoreId(28);
			order.setStoreName("压力测试");
			order.setPayStatus(3);
			order.setOpenId("123");
			order.setTotalMoney(new BigDecimal(0.01));
			order.setTableId("1111");
			storeOrder.insertOrder(order);
		}
		return "数据添加成功!";
	}

	@RequestMapping("/testMy")
	public void testMy(Integer num) throws Exception {
		test(num);
	}

	@RequestMapping("/addSession")
	@ResponseBody
	public boolean addSession(HttpSession session) throws Exception {
		try {
			log.info("测试addSession");
			session.setAttribute("openId", "123");
			session.setAttribute("storeId", 28);
			return true;
		} catch (Exception e) {
			return false;
		}

	}

	public void test(Integer index) throws Exception {
		for (int i = 0; i < index; i++) {
			log.info("====柱子测试====" + i);
			final Map<String, String> map = new HashMap<String, String>();

			map.put("orderNumber", "2019030811230824" + i);
			map.put("total", "0.01");
			MyThreadPoolManager.getInstance().execute(new Runnable() {

				@Override
				public void run() {
					try {
						log.info("11111" + map.toString());
						// 测试检测版本信息接口
						String resStr = TestMy
								.httpRequest(
										"http://i4uk5e.natappfree.cc/handordering/StoreXhPayController/toXhPay",
										"POST", TestMy.transParameter(map));

					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});

		}

	}

	public void testThread(Integer index) throws Exception {
		for (int i = 0; i < index; i++) {
			log.info("====柱子测试线程====" + i);
			TestThread testThread = new TestThread();
			testThread.start();
		}

	}

	/**
	 * 请求参数转化
	 * 
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public static String transParameter(Map<String, String> map)
			throws Exception {
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			sb.append(entry.getKey()).append("=");
			sb.append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&");
		}
		return sb.toString();
	}

	/**
	 * 发起http或https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式(GET、POST)
	 * @param outputStr
	 *            提交的数据
	 * 
	 */
	@SuppressWarnings("unused")
	public static String httpRequest(String requestUrl, String requestMethod,
			String outputStr) {
		log.info("接收的参数:" + requestUrl + "," + requestMethod + "," + outputStr);

		StringBuffer buffer = new StringBuffer();
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url
					.openConnection();

			log.info("httpUrlConn:" + httpUrlConn);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);

			httpUrlConn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");

			// 设置请求方式(GET/POST)
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod)) {
				httpUrlConn.connect();
				log.info("get请求");

			}

			// 当有数据需要提交时
			if (null != outputStr && !"".equals(outputStr)) {
				log.info("========================================");
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式,防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.flush();
				outputStream.close();
			}
			int A = HttpURLConnection.HTTP_OK;
			int B = httpUrlConn.getResponseCode();
			if (HttpURLConnection.HTTP_OK != httpUrlConn.getResponseCode()) {
				System.out.println("httpUrlConn.getResponseCode():"
						+ httpUrlConn.getResponseCode());
			}
			if (HttpURLConnection.HTTP_OK != httpUrlConn.getResponseCode()) {
				System.out.println("httpUrlConn.getResponseCode():"
						+ httpUrlConn.getResponseCode());
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			return buffer.toString();
		} catch (ConnectException ce) {
			// log.error("server connection timed out.");
			System.out.println(ce.getMessage());
		} catch (Exception e) {
			System.out.println(e.getMessage());
			// log.error("https request error:{}", e);
		}
		return null;
	}

}

猜你喜欢

转载自blog.csdn.net/xinpz/article/details/88396815