2016-01-05 16 views
0

我有文件,其中包含文本是這樣的在文件中使用加特林遍歷一行一行地在同一時間發送一個消息,以卡夫卡

{"content_type":"Twitter","id":"77f985b0-a30a-11e5-8791-80000bc51f65","source_id":"676656486307639298","date":"2015-12-15T06:54:12.000Z","text":"RT @kokodeikku_bot: ?????: ??,} 
{"content_type":"Twitter","id":"7837a020-a30a-11e5-8791-80000bc51f65","source_id":"676656494700568576",} 
{"content_type":"Twitter","id":"7838d8a0-a30a-11e5-8791-80000bc51f65","source_id":"676656507266703360",} 

我無法在一次讀取每一行作爲字符串轉換爲場景中的Kafka主題,因爲我無法遍歷Gatling中的場景。

這裏是我的代碼

class KafkaSimulation extends Simulation { 

    val line = Source.fromFile(<passing locn of file>)("UTF-8").getLines.mkString("\n") // one way by reading source from file 

    val br = new BufferedReader(new FileReader("<passing locn of file>")) 
    var line:String = "" 

    while ({ line = br.readLine() ; line != null }) { 
     //In this while loop i can print line by line but i cant use while loop within scenario below 
     println(listOfLines.mkString("\n"))  
     } 

    val kafkaConf = kafka 

    // Kafka topic name 
    .topic("test") 
    // Kafka producer configs 
    .properties(
     Map(
     ProducerConfig.ACKS_CONFIG -> "1", 
     // list of Kafka broker hostname and port pairs 
      ProducerConfig.BOOTSTRAP_SERVERS_CONFIG -> "localhost:9092", 
     // Required since Apache Kafka 0.8.2.0 
     ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG -> 
      "org.apache.kafka.common.serialization.ByteArraySerializer", 
     ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG -> 
      "org.apache.kafka.common.serialization.ByteArraySerializer")) 

    val scn = scenario("Kafka Test") 
    .exec(kafka("request") 
     // message to send 
     .send(line.toString())) //Here if i put line.toString(), it doesnt read line by line instead it will post entire 3 lines as one message 

    setUp(
     scn.inject(constantUsersPerSec(10) during (1 seconds))) 
    .protocols(kafkaConf) 

} 

對我怎麼能遍歷一個文件,並在場景一行一行讀任何提示?

回答

1

將您的文件轉換爲一列CSV Feeder,並使用標準的Gatling方式:提供記錄,發送您的請求,然後重複您想要的。

+0

感謝Stephane爲您的快速響應。它現在可以工作,但是有一個問題,儘管將該行發佈到Apache Kafka,它將大括號中的第一個雙引號括起來作爲{content_type「:而不是將其作爲{」content_type「發送:可能是文件的某些編碼問題但很多感謝 – user1459742

+0

Feeder只是一個迭代器[Map [String,Any]]。您可以使用Source.getLines輕鬆解析文件,並將這些行映射爲一個具有單個條目的Map。 –

0

對於這個目標,你真正需要的唯一東西就是打開文件並逐行遍歷它。 @stephane評論有點生,不過他的意思是:

Source 
    .fromFile("files/yourtargetfile.txt") 
    .getLines 
    .map { line => 
    //do your stuff 
    }.foreach(println) 

或者,更簡單的東西,如果你不想要編輯的文件的內容:

Source 
    .fromFile("files/ChargeNames") 
    .getLines 
    .foreach { line => 
    //do your stuff 
    } 

我希望這有助於, 乾杯。

相關問題