2015-05-04 4 views
2

Я использую jmeter для создания HTTP-запроса для моего веб-сервиса REST. Теперь я хочу отправить этот запрос в Amazon kinesis с использованием метода PutRecords, но я не знаю, как hot создать запрос, в частности, как установить поля заголовков для подписи и аутентификации в кинезисе. Кто-нибудь использовал запрос на отдых? благодаряИспользование HTTP-запроса Jmeter для размещения записей в Amazon Kinesis

+0

Вы пробовали использовать менеджер заголовка? http://jmeter.apache.org/usermanual/component_reference.html#HTTP_Header_Manager – RaGe

+0

Да, я использовал диспетчер заголовков, но я новичок в кинезисе, поэтому я не знаю названия заголовка и значения, которое я должен установить – luca

ответ

0

Этот вопрос стар, и я не помню все, но это код, если кто-то нужно: BeanShell Sampler

import org.MyKinesisClient; 

//Create a controller object every time Jmeter starts 
MyKinesisClient controller=new MyKinesisClient(vars.get("accessKey"),vars.get("secretKey"),vars.get("endpoint"),vars.get("serviceName"),vars.get("regionId")); 
bsh.shared.controller=controller; 

Это последний код:

import com.amazonaws.util.json.JSONArray; 
import com.amazonaws.util.json.JSONObject; 
import org.MyKinesisClient; 

//Variables 
int timestampValue=(${i}); 
String idValue=${__threadNum}+"_"+"1"; 
JSONObject part = new JSONObject(); 

//Inserimento campi Json 
part.put("updated",timestampValue); 
part.put("parent","${__threadNum}"); 
part.put("id",idValue); 
part.put("thingClass","CosyInverter"); 
part.put("mac_address_w","${mac_address_w_1}"); 
//Other put 
.... 

//Send Json to kinesis 
MyKinesisClient controller=bsh.shared.controller; 
controller.sendJson(part, ${__Random(0,${__threadNum})},vars.get("streamName")); 

Мой код сложнее, чем выше (запрос базы данных и т. д.), но я надеюсь, что это то, что вам нужно.

Это ява код о MyKinesisClient

import java.io.UnsupportedEncodingException; 
import java.nio.ByteBuffer; 
import java.util.ArrayList; 
import java.util.List; 

import com.amazonaws.auth.AWSCredentials; 
import com.amazonaws.auth.BasicAWSCredentials; 
import com.amazonaws.services.kinesis.AmazonKinesisClient; 
import com.amazonaws.services.kinesis.model.PutRecordRequest; 
import com.amazonaws.services.kinesis.model.PutRecordsRequest; 
import com.amazonaws.services.kinesis.model.PutRecordsRequestEntry; 
import com.amazonaws.util.json.JSONArray; 
import com.amazonaws.util.json.JSONException; 
import com.amazonaws.util.json.JSONObject; 

/** 
* Class useful to send Json to Amazon Kinesis. 
* @author l.calicchio 
* 
*/ 
public class MyKinesisClient { 
    private AmazonKinesisClient kinesisClient; 

    /** 
    * Class constructor. Allow all parameter setting 
    * @param accessKey: access key for kinesis connection 
    * @param secretKey: secret key for kinesis connection 
    * @param endpoint: Kinesis endpoint 
    * @param serviceName: Amazon service name 
    * @param regionId: region id of kinesis endpoint 
    */ 
    public MyKinesisClient(String accessKey, String secretKey, String endpoint, String serviceName, String regionId) { 
     AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); 
     kinesisClient = new AmazonKinesisClient(credentials); 
     kinesisClient.setEndpoint(endpoint,serviceName,regionId); 
    } 

    /** 
    * Method useful to send the json to Kinesis 
    * @param json: com.amazonaws.util.json.JSONObject to be sent 
    * @param partitionKey: partition key for Kinesis stream 
    * @param streamName: name of Kinesis stream 
    * @throws UnsupportedEncodingException 
    * @throws JSONException 
    */ 
    public void sendJson(JSONObject json, int partitionKey, String streamName) throws UnsupportedEncodingException, JSONException { 
     try{ 
     PutRecordRequest putRecordRequest = new PutRecordRequest(); 
     putRecordRequest.setStreamName(streamName); 
     putRecordRequest.setData(ByteBuffer.wrap(json.toString().getBytes("utf-8"))); 
     putRecordRequest.setPartitionKey(String.format("partitionKey-%d", partitionKey)); 
     kinesisClient.putRecord(putRecordRequest); 
     }catch(Exception e){ 
      System.out.println(e.getMessage()); 
     } 
    } 

    /** 
    * Method useful to send the json Array to Kinesis 
    * @param json: com.amazonaws.util.json.JSONObject Array to be sent 
    * @param partitionKey: partition key for Kinesis stream 
    * @param streamName: Kinesis stream name 
    */ 
    public void sendJsonArray(JSONArray json,int partitionKey, String streamName) { 
     try{ 
     PutRecordsRequest putRecordsRequest = new PutRecordsRequest(); 
     putRecordsRequest.setStreamName(streamName);    
     List <PutRecordsRequestEntry> putRecordsRequestEntryList = new ArrayList<PutRecordsRequestEntry>(); 
     for(int i=0;i<json.length();i++){   
      PutRecordsRequestEntry putRecordsRequestEntry = new PutRecordsRequestEntry(); 
      putRecordsRequestEntry.setData(ByteBuffer.wrap(json.getJSONObject(i).toString().getBytes("utf-8"))); 
      putRecordsRequestEntry.setPartitionKey(String.format("partitionKey-%d", partitionKey)); 
      putRecordsRequestEntryList.add(putRecordsRequestEntry); 
     } 
     putRecordsRequest.setRecords(putRecordsRequestEntryList); 
     kinesisClient.putRecords(putRecordsRequest); 
     }catch(Exception e){ 
      System.out.println(e.getMessage()); 
     } 
    } 
} 
0

Согласно PutRecords API reference образца запрос должен выглядеть, как

POST/HTTP/1.1 
Host: kinesis.<region>.<domain> 
x-amz-Date: <Date> 
Authorization: AWS4-HMAC-SHA256 Credential=<Credential>,  SignedHeaders=content-type;date;host;user-agent;x-amz-date;x-amz-target;x- amzn-requestid, Signature=<Signature> 
User-Agent: <UserAgentString> 
Content-Type: application/x-amz-json-1.1 
Content-Length: <PayloadSizeBytes> 
Connection: Keep-Alive 
X-Amz-Target: Kinesis_20131202.PutRecords 

Так, по крайней мере требуется следующее:

  • Content-Type
  • X-Amz-Target
  • Авторизация
  • x-amz-date

Вы можете добавить HTTP Header Manager, чтобы добавить их в ваши пожелания.

JMeter должен заполнить Content-Length, Connection и Host самостоятельно.

+0

спасибо, но я имеют только имя пользователя, идентификатор ключа доступа, секретный ключ доступа, как я могу сделать заголовок http через это значение? Я думаю, что проблема заключается в подписи. Я также пытаюсь импортировать AmazonKinesisClient в Jmeter, чтобы я мог использовать Beanshell, но импорт не работает (в jar-файле класс не существует, но в eclipse корректен импорт) – luca

+0

любая удача с этим? – Marko

+0

В конце концов я использовал API Amazon Kinesis через java-код в Jmeter – luca

Смежные вопросы