ngrinder 负载均衡脚本开发
config.py
# -*- coding: utf-8 -*-
cookies = []
userids = []
infile = open("./resources/test_auth_1W_1.txt", 'rb')
for line in infile.readlines():
userids.append(line.strip().split(",")[0])
cookies.append(line.strip().split(",")[1])
infile.close()
putongGoodsIds = []
infile = open("./resources/goods_putong1.txt", 'rb')
for line in infile.readlines():
putongGoodsIds.append(line.strip().split(",")[1])
infile.close()
putong2GoodsIds = []
infile = open("./resources/goods_putong2.txt", 'rb')
for line in infile.readlines():
putong2GoodsIds.append(line.strip().split(",")[1])
infile.close()
# gateway 网关负载均衡 30台机器
gateways = ["192.168.8.126:8080","192.168.8.127:8080","192.168.8.128:8080","192.168.102.6:8080","192.168.102.7:8080","192.168.102.8:8080","192.168.102.9:8080","192.168.102.10:8080","192.168.102.11:8080","192.168.102.12:8080","192.168.102.13:8080","192.168.102.14:8080","192.168.102.15:8080","192.168.102.16:8080","192.168.102.17:8080","192.168.102.18:8080","192.168.102.19:8080","192.168.102.20:8080","192.168.102.21:8080","192.168.102.22:8080","192.168.104.97:8080","192.168.104.98:8080","192.168.104.117:8080","192.168.104.139:8080","192.168.104.140:8080","192.168.104.141:8080","192.168.104.142:8080","192.168.104.143:8080","192.168.104.144:8080","192.168.104.145:8080"]
# -*- coding: utf-8 -*-
'''
下单链路:确认订单、生成订单
选取店铺 3381 3380 下面的商品(每个店铺160个普通商品,4种店铺优惠)
下单链路_普通会员
'''
from net.grinder.script import Test
from net.grinder.script.Grinder import grinder
from HTTPClient import NVPair
from net.grinder.plugin.http import HTTPRequest
from net.grinder.plugin.http import HTTPPluginControl
from java.util import Random
from org.slf4j import LoggerFactory
from ch.qos.logback.classic import Level
from com.alibaba.fastjson import JSON
from Config import cookies, gateways, putongGoodsIds, putong2GoodsIds
case_no_1 = 1
case_name_1 = "api_buy_confirmOrder"
case_no_2 = 2
case_name_2 = "api_buy_createOrder"
connectionDefaults = HTTPPluginControl.getConnectionDefaults()
connectionDefaults.timeout = 60000 # 超时时间设置 60秒
httpUtilities = HTTPPluginControl.getHTTPUtilities()
HTTPPluginControl.getConnectionDefaults().useCookies = 0
totalAgents = int(grinder.getProperties().get('grinder.agents'))
totalProcess = int(grinder.getProperties().get('grinder.processes'))
totalThreads = int(grinder.getProperties().get('grinder.threads'))
class TestRunner:
def __init__(self):
logger = LoggerFactory.getLogger("worker");
logger.setLevel(Level.ERROR);
grinder.statistics.delayReports=True
pass
def getIncrementId(self, runNumber):
agentNum = grinder.agentNumber
processNum = grinder.processNumber
threadNum = grinder.threadNumber
return agentNum * totalProcess * totalThreads + processNum * totalThreads + threadNum + totalAgents * totalProcess * totalThreads * runNumber
def api_buy_confirmOrder(self, url, body, header):
result = HTTPRequest(url=url, headers=header).POST(url, body)
data = result.getText().encode('utf-8')
#print data # 调试使用,压测时关闭
try:
addressId = JSON.parseObject(data).getJSONObject("data").getJSONObject("address").getString("addressId")
idCardId = JSON.parseObject(data).getJSONObject("data").getJSONObject("identity").getString("idCardId")
# 商品1的优惠信息-普通品
promotionKey_putong_1 = JSON.parseObject(data).getJSONObject("data").getJSONArray("shopOrderList")[0]["selectedPromotionList"][0]["promotionKey"]
SINGLE_ITEM_putong_1 = JSON.parseObject(data).getJSONObject("data").getJSONArray("shopOrderList")[0]["itemOrderList"][0]["selectedPromotionList"][0]["promotionKey"]
logisticsCode_putong_1 = JSON.parseObject(data).getJSONObject("data").getJSONArray("shopOrderList")[0]["selectedLogistics"]["logisticsCode"]
# 商品2的优惠信息-普通品
MEMBER_PRICE_putong_2 = JSON.parseObject(data).getJSONObject("data").getJSONArray("shopOrderList")[1]["itemOrderList"][0]["selectedPromotionList"][0]["promotionKey"]
logisticsCode_putong_2 = JSON.parseObject(data).getJSONObject("data").getJSONArray("shopOrderList")[1]["selectedLogistics"]["logisticsCode"]
except:
grinder.logger.error(case_name_1 + ':' + body + ':' + data.decode('utf-8'))
if(result.getStatusCode() != 200 or data.find('"status":0') != -1 or data.find('"code":0') == -1):
grinder.getStatistics().getForCurrentTest().setSuccess(False)
grinder.logger.error(case_name_1 + ':' + body + ':' + data.decode('utf-8'))
return addressId, idCardId, promotionKey_putong_1, SINGLE_ITEM_putong_1, logisticsCode_putong_1, MEMBER_PRICE_putong_2, logisticsCode_putong_2
def api_buy_createOrder(self, url, body, header):
result = HTTPRequest(url=url, headers=header).POST(url, body)
data = result.getText().encode('utf-8')
#print data # 调试使用,压测时关闭
if(result.getStatusCode() != 200 or data.find('"status":0') != -1 or data.find('"code":0') == -1):
grinder.getStatistics().getForCurrentTest().setSuccess(False)
grinder.logger.error(case_name_2 + ':' + body + ':' + data.decode('utf-8'))
request_1 = Test(case_no_1, case_name_1).wrap(api_buy_confirmOrder)
request_2 = Test(case_no_2, case_name_2).wrap(api_buy_createOrder)
def __call__(self):
index_num = self.getIncrementId(grinder.runNumber)
index = index_num % len(cookies)
index_1 = index_num % len(putongGoodsIds)
index_2 = index_num % len(putong2GoodsIds)
header = [
NVPair('Content-Type', 'application/x-www-form-urlencoded'),
NVPair('cookie', cookies[index])
]
url_1 = 'http://' + gateways[index_num % 30] + '/buy/api/buy/confirmOrder'
body_1 = 'createOrderBizContent={"extensions":{"buySource":"itemDetail"},"addressId":"-1","createOrderShopGroupList":[{"logisticsCode":"","createOrderSkuGroupList":[{"extensions":{},"quantity":"1","selectedPromotionList":[],"skuId":"%s"},{"extensions":{},"quantity":1,"selectedPromotionList":[],"skuId":"%s"}],"comment":"perf_test","selectedPromotionList":[]}],"idCardId":"-1","selectedPromotionList":[],"coinToUse":"-1"}' %(putongGoodsIds[index_1], putong2GoodsIds[index_2])
addressId, idCardId, promotionKey_putong_1, SINGLE_ITEM_putong_1, logisticsCode_putong_1, MEMBER_PRICE_putong_2, logisticsCode_putong_2 = self.request_1(url_1,body_1,header)
url_2 = 'http://' + gateways[index_num % 30] + '/buy/api/buy/createOrder'
body_2 = 'createOrderBizContent={"idCardId":%s,"addressId":%s,"selectedPromotionList":[],"extensions":{"buySource":"cart"},"createOrderShopGroupList":[{"comment":"","extensions":{},"logisticsCode":"%s","selectedPromotionList":["%s"],"createOrderSkuGroupList":[{"extensions":{},"selectedPromotionList":["%s"],"skuId":%s,"quantity":1}]},{"comment":"","extensions":{},"logisticsCode":"%s","selectedPromotionList":[],"createOrderSkuGroupList":[{"extensions":{},"selectedPromotionList":["%s"],"skuId":%s,"quantity":1}]}]}' %(idCardId, addressId, logisticsCode_putong_1, promotionKey_putong_1, SINGLE_ITEM_putong_1, putongGoodsIds[index_1], logisticsCode_putong_2, MEMBER_PRICE_putong_2, putong2GoodsIds[index_2])
self.request_2(url_2,body_2,header)