程序員的簡單接口壓測

接口必然需要壓測,但有時候往往沒有專門壓測人員,程序員自己動手。以實名接口爲例,傳入姓名、×××號上有返回一致、不一致等信息,一致信息則插入用戶信息表,下次調用時先查詢該表,如果有直接返回結果。

1.restful接口
使用springboot很容易搭建接口,過程略

2.造數據
2.1java批量插入數據,略
2.2存儲過程造數據
2.3sql造數據

-- 建表
drop table if exists `t_identity_info`;
create table `t_identity_info` (
  `id` int(11) not null auto_increment comment '主鍵id',
  `real_name` varchar(20) default null comment '姓名',
  `id_card` varchar(18) not null comment '×××號',
  `create_time` varchar(19) not null comment '創建時間',
  primary key (`id`),
  key `index_id_card` (`id_card`)
) engine=innodb auto_increment=1 default charset=utf8 comment='用戶信息表';

-- 存儲過程
drop procedure if exists insert_t_identity_info_data;

delimiter ;;
create procedure insert_t_identity_info_data()
begin 
declare i int;
declare tempName varchar(4);
declare tempAreaCode varchar(6);
declare tempDate varchar(8);

set i = 0;
while i < 10000 do
set tempAreaCode = concat((CEILING(RAND()*1000 mod 50) + 10),(CEILING(RAND()*1000 mod 50) + 10),(CEILING(RAND()*1000 mod 50) + 10)) ; 
set tempDate = DATE_FORMAT(date_add(now(), interval - CEILING(RAND()*1000000 mod 10000) day),'%Y%m%d');
set tempName = concat(substring('趙錢孫李周吳鄭王馮陳褚衛蔣沈韓',CEILING(RAND()*1000 mod 15),1),
substring('嘉懿煜城懿軒燁偉苑博偉澤熠彤鴻',CEILING(RAND()*1000 mod 15),1));

insert into t_identity_info (real_name,id_card,create_time) values 
(tempName,concat(tempDate,CEILING(RAND()*100000) mod 9999+1000),now()),
(tempName,concat(tempDate,CEILING(RAND()*100000) mod 9999+1000),now()),
(tempName,concat(tempDate,CEILING(RAND()*100000) mod 9999+1000),now()),
(tempName,concat(tempDate,CEILING(RAND()*100000) mod 9999+1000),now()),
(tempName,concat(tempDate,CEILING(RAND()*100000) mod 9999+1000),now()),
(tempName,concat(tempDate,CEILING(RAND()*100000) mod 9999+1000),now()),
(tempName,concat(tempDate,CEILING(RAND()*100000) mod 9999+1000),now()),
(tempName,concat(tempDate,CEILING(RAND()*100000) mod 9999+1000),now()),
(tempName,concat(tempDate,CEILING(RAND()*100000) mod 9999+1000),now()),
(tempName,concat(tempDate,CEILING(RAND()*100000) mod 9999+1000),now());
select count(1) from t_identity_info;
set i = i +1; 

end while; 
end 
;;
DELIMITER ;

-- 調用存儲過程
call insert_t_identity_info_data();

-- 循環造數據,執行一次數據量*2
insert into t_identity_info(real_name,id_card,create_time) select real_name,id_card,now() from t_identity_info;

完成接口的httpclient

3.壓測
運行spring boot
運行n個接口客戶端

注意:
不要在本機壓測,數據庫、服務、客戶端都應在服務器上,
壓測至少半個小時,根據tps啓動客戶端個數、每個客戶端的數量;
檢測服務器的內存、cpu;
考慮網絡瓶頸。

package com.ld.api;

import java.util.Date;
import java.util.Map;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.ld.util.LoggerUtil;

@RestController
@RequestMapping("/identity")
public class IdentityApi {

    private static final Logger logger = LoggerFactory.getLogger(LoggerUtil.class);

    @PostMapping("/check")
    public String check(@RequestBody Map<String, String> map) {
        String transNo = getTransNoByType("identityCheck");
        long beginTime = System.currentTimeMillis();
        logger.info("transNo = {} , map = {}", transNo, map);

        // 查詢db
        sleepSomeTime();

        // 返回結果
        String result = null;

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("transNo", transNo);
            jsonObject.put("state", System.currentTimeMillis() % 2 + 1);
            jsonObject.put("costTime", System.currentTimeMillis() - beginTime);// 接口耗費時間
        } catch (Exception e) {
            e.printStackTrace();
        }

        result = jsonObject.toString();
        logger.info("transNo = {} , result = {}", transNo, result);
        return result;
    }

    /**
     * 通過流水號串聯日誌,方便定位問題
     * 
     * @param transNoType
     * @return 2019年3月27日
     */
    private String getTransNoByType(String transNoType) {
        return transNoType + "_" + DateFormatUtils.format(new Date(), "yyMMddHHmm") + "_"
                + RandomStringUtils.randomAlphabetic(4);
    }

    /**
     * 隨機休眠
     * 
     * 2019年3月27日
     */
    private void sleepSomeTime() {
        try {
            Thread.sleep(System.currentTimeMillis() % 300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

package com.ld;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class IdentityCheck {
    public static void main(String[] args) {
        try {

            for (int i = 0; i < 100; i++) {
                check();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void check() throws Exception {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        String loginUrl = "http://localhost:8080/identity/check";

        HttpPost httppost = new HttpPost(loginUrl);
        httppost.addHeader("Content-Type", "application/json;charset=UTF-8");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("idCard", "131024199901010011");
        jsonObject.put("realName", "李四");

        StringEntity stringEntity = new StringEntity(jsonObject.toString(), "utf-8");
        httppost.setEntity(stringEntity);

        CloseableHttpResponse response = httpclient.execute(httppost);
        System.out.println("response = " + response.toString());

        HttpEntity entity = response.getEntity();
        String jsonStr = EntityUtils.toString(entity, "utf-8");
        System.out.println("jsonStr = " + jsonStr);

        httppost.releaseConnection();
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章