MQTT Protocol
How to use the MQTT support in Gatling to connect to a broker and perform checks against inbound messages.
mqttVersion_5 on the protocol to use the options marked as MQTT 5 only on this page.
Gatling doesn’t support MQTT 5 topic aliases and enhanced authentication.Prerequisites
Gatling Enterprise MQTT SDK is not imported by default.
You have to manually add the following imports:
import io.gatling.javaapi.mqtt.*;
import static io.gatling.javaapi.mqtt.MqttDsl.*;import { mqtt } from "@gatling.io/mqtt";import io.gatling.javaapi.mqtt.MqttDsl.*import io.gatling.mqtt.Predef._MQTT protocol
Use the mqtt object in order to create a MQTT protocol.
MqttProtocolBuilder mqttProtocol = mqtt
// enable protocol version 3.1
.mqttVersion_3_1()
// enable protocol version 3.1.1 (default protocol version)
.mqttVersion_3_1_1()
// enable protocol version 5
.mqttVersion_5()
// broker address (default: localhost:1883)
.broker("hostname", 1883)
// if TLS should be enabled (default: false)
.useTls(true)
// Used to specify KeyManagerFactory for each individual virtual user. Input is the 0-based incremental id of the virtual user.
.perUserKeyManagerFactory(
userId -> {
try {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
// P12 files stored under src/test/resources/keys
try (InputStream is =
getClass()
.getClassLoader()
.getResourceAsStream("keys/pk-" + userId + ".p12")) {
keyStore.load(is, null);
}
KeyManagerFactory kmf =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, null);
return kmf;
} catch (Exception e) {
throw new RuntimeException(e);
}
})
// clientIdentifier sent in the connect payload (of not set, Gatling will generate a random one)
.clientId("#{id}")
// if session should be cleaned during connect (default: true)
.cleanSession(true)
// optional credentials for connecting
.credentials("#{userName}", "#{password}")
// connections keep alive timeout
.keepAlive(30)
// use at-most-once QoS (default: true)
.qosAtMostOnce()
// use at-least-once QoS (default: false)
.qosAtLeastOnce()
// use exactly-once QoS (default: false)
.qosExactlyOnce()
// enable retain (default: false)
.retain(false)
// send last will, possibly with specific QoS and retain
.lastWill(
LastWill("#{willTopic}", StringBody("#{willMessage}"))
.qosAtLeastOnce()
.retain(true)
)
// max number of reconnects after connection crash (default: 3)
.reconnectAttemptsMax(1)
// reconnect delay after connection crash in millis (default: 100)
.reconnectDelay(1)
// reconnect delay exponential backoff (default: 1.5)
.reconnectBackoffMultiplier(1.5F)
// resend delay after send failure in millis (default: 5000)
.resendDelay(1000)
// resend delay exponential backoff (default: 1.0)
.resendBackoffMultiplier(2.0F)
// interval for timeout checker (default: 1 second)
.timeoutCheckInterval(1)
// check for pairing messages sent and messages received
.correlateBy(check)
// enable unmatched MQTT inbound messages buffering,
// with a max buffer size of 5
.unmatchedInboundMessageBufferSize(5);const mqttProtocol = mqtt
// enable protocol version 3.1
.mqttVersion_3_1()
// enable protocol version 3.1.1 (default protocol version)
.mqttVersion_3_1_1()
// enable protocol version 5
.mqttVersion_5()
// broker address (default: localhost:1883)
.broker("hostname", 1883)
// if TLS should be enabled (default: false)
.useTls(true)
// clientIdentifier sent in the connect payload (of not set, Gatling will generate a random one)
.clientId("#{id}")
// if session should be cleaned during connect (default: true)
.cleanSession(true)
// optional credentials for connecting
.credentials("#{userName}", "#{password}")
// connections keep alive timeout
.keepAlive(30)
// use at-most-once QoS (default: true)
.qosAtMostOnce()
// use at-least-once QoS (default: false)
.qosAtLeastOnce()
// use exactly-once QoS (default: false)
.qosExactlyOnce()
// enable retain (default: false)
.retain(false)
// send last will, possibly with specific QoS and retain
.lastWill(
LastWill("#{willTopic}", StringBody("#{willMessage}"))
.qosAtLeastOnce()
.retain(true)
)
// max number of reconnects after connection crash (default: 3)
.reconnectAttemptsMax(1)
// reconnect delay after connection crash in millis (default: 100)
.reconnectDelay(1)
// reconnect delay exponential backoff (default: 1.5)
.reconnectBackoffMultiplier(1.5)
// resend delay after send failure in millis (default: 5000)
.resendDelay(1000)
// resend delay exponential backoff (default: 1.0)
.resendBackoffMultiplier(2.0)
// interval for timeout checker (default: 1 second)
.timeoutCheckInterval(1)
// check for pairing messages sent and messages received
.correlateBy(check)
// enable unmatched MQTT inbound messages buffering,
// with a max buffer size of 5
.unmatchedInboundMessageBufferSize(5);val mqttProtocol = mqtt
// enable protocol version 3.1
.mqttVersion_3_1()
// enable protocol version 3.1.1 (default protocol version)
.mqttVersion_3_1_1()
// enable protocol version 5
.mqttVersion_5()
// broker address (default: localhost:1883)
.broker("hostname", 1883)
// if TLS should be enabled (default: false)
.useTls(true)
// Used to specify KeyManagerFactory for each individual virtual user. Input is the 0-based incremental id of the virtual user.
.perUserKeyManagerFactory { userId ->
val keyStore = KeyStore.getInstance("PKCS12")
// P12 files stored under src/test/resources/keys
javaClass.classLoader.getResourceAsStream("keys/pk-$userId.p12")!!.use {
keyStore.load(it, null)
}
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()).apply {
init(keyStore, null)
}
}
// clientIdentifier sent in the connect payload (of not set, Gatling will generate a random one)
.clientId("#{id}")
// if session should be cleaned during connect (default: true)
.cleanSession(true)
// optional credentials for connecting
.credentials("#{userName}", "#{password}")
// connections keep alive timeout
.keepAlive(30)
// use at-most-once QoS (default: true)
.qosAtMostOnce()
// use at-least-once QoS (default: false)
.qosAtLeastOnce()
// use exactly-once QoS (default: false)
.qosExactlyOnce()
// enable retain (default: false)
.retain(false)
// send last will, possibly with specific QoS and retain
.lastWill(
LastWill("#{willTopic}", StringBody("#{willMessage}"))
.qosAtLeastOnce()
.retain(true)
)
// max number of reconnects after connection crash (default: 3)
.reconnectAttemptsMax(1)
// reconnect delay after connection crash in millis (default: 100)
.reconnectDelay(1)
// reconnect delay exponential backoff (default: 1.5)
.reconnectBackoffMultiplier(1.5f)
// resend delay after send failure in millis (default: 5000)
.resendDelay(1000)
// resend delay exponential backoff (default: 1.0)
.resendBackoffMultiplier(2.0f)
// interval for timeout checker (default: 1 second)
.timeoutCheckInterval(1)
// check for pairing messages sent and messages received
.correlateBy(check)
// enable unmatched MQTT inbound messages buffering,
// with a max buffer size of 5
.unmatchedInboundMessageBufferSize(5)val mqttProtocol = mqtt
// enable protocol version 3.1
.mqttVersion_3_1
// enable protocol version 3.1.1 (default protocol version)
.mqttVersion_3_1_1
// enable protocol version 5
.mqttVersion_5
// broker address (default: localhost:1883)
.broker("hostname", 1883)
// if TLS should be enabled (default: false)
.useTls(true)
// Used to specify KeyManagerFactory for each individual virtual user. Input is the 0-based incremental id of the virtual user.
.perUserKeyManagerFactory { userId =>
val keyStore = KeyStore.getInstance("PKCS12")
// P12 files stored under src/test/resources/keys
Using(getClass.getClassLoader.getResourceAsStream("keys/pk-" + userId + ".p12")) {
keyStore.load(_, null)
}
val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm)
kmf.init(keyStore, null)
kmf
}
// clientIdentifier sent in the connect payload (of not set, Gatling will generate a random one)
.clientId("#{id}")
// if session should be cleaned during connect (default: true)
.cleanSession(true)
// optional credentials for connecting
.credentials("#{userName}", "#{password}")
// connections keep alive timeout
.keepAlive(30)
// use at-most-once QoS (default: true)
.qosAtMostOnce
// use at-least-once QoS (default: false)
.qosAtLeastOnce
// use exactly-once QoS (default: false)
.qosExactlyOnce
// enable retain (default: false)
.retain(false)
// send last will, possibly with specific QoS and retain
.lastWill(
LastWill("#{willTopic}", StringBody("#{willMessage}"))
.qosAtLeastOnce
.retain(true)
)
// max number of reconnects after connection crash (default: 3)
.reconnectAttemptsMax(1)
// reconnect delay after connection crash in millis (default: 100)
.reconnectDelay(1)
// reconnect delay exponential backoff (default: 1.5)
.reconnectBackoffMultiplier(1.5F)
// resend delay after send failure in millis (default: 5000)
.resendDelay(1000)
// resend delay exponential backoff (default: 1.0)
.resendBackoffMultiplier(2.0F)
// interval for timeout checker (default: 1 second)
.timeoutCheckInterval(1)
// check for pairing messages sent and messages received
.correlateBy(check)
// enable unmatched MQTT inbound messages buffering,
// with a max buffer size of 5
.unmatchedInboundMessageBufferSize(5)Use per virtual user client certificates
With useTls(true), you can provide a client certificate for each virtual user with perUserKeyManagerFactory, either with a function that returns a javax.net.ssl.KeyManagerFactory (see the sample above) or, more simply, by storing all your keys in a single PKCS#12 file with one key entry (alias) per virtual user.
The password is optional.
// keys/multi-alias.p12 is a PKCS#12 file with one key entry per virtual user
mqtt.perUserKeyManagerFactory("keys/multi-alias.p12", "password");
// no password
mqtt.perUserKeyManagerFactory("keys/multi-alias.p12");// keys/multi-alias.p12 is a PKCS#12 file with one key entry per virtual user
mqtt.perUserKeyManagerFactory("keys/multi-alias.p12", "password");
// no password
mqtt.perUserKeyManagerFactory("keys/multi-alias.p12");// keys/multi-alias.p12 is a PKCS#12 file with one key entry per virtual user
mqtt.perUserKeyManagerFactory("keys/multi-alias.p12", "password")
// no password
mqtt.perUserKeyManagerFactory("keys/multi-alias.p12")// keys/multi-alias.p12 is a PKCS#12 file with one key entry per virtual user
mqtt.perUserKeyManagerFactory("keys/multi-alias.p12", "password")
// no password
mqtt.perUserKeyManagerFactory("keys/multi-alias.p12")Note that:
- The file is located either on the classpath or as an absolute path on the filesystem.
- Key entries are assigned to virtual users in the alphabetical order of their aliases: the virtual user with id 1 gets the first alias, and so on.
- Each key entry is used by one single virtual user. If the file contains fewer key entries than virtual users, the run is stopped.
- On Gatling Enterprise with multiple load generators, aliases are split so that each load generator gets its own distinct subset, hence a key entry is never used by 2 different load generators.
See HTTP protocol for a sample script that generates such a keystore.
Resolve the broker hostname
Gatling resolves the broker hostname on each connect and reconnect, and picks a random address among the resolved ones, so virtual users spread over all the broker’s addresses and follow DNS changes. A DNS resolution failure fails the connect and triggers a reconnect.
By default, Gatling uses Java’s blocking DNS resolver, like the HTTP protocol.
Use asyncNameResolution to switch to Gatling’s non-blocking DNS resolver, and perUserNameResolution to give each virtual user its own DNS cache.
These options work like their HTTP protocol counterparts.
// resolve the broker hostname with Gatling's non-blocking DNS resolver,
// using the system's DNS servers
mqtt.asyncNameResolution();
// force DNS servers, as "host" or "host:port"
mqtt.asyncNameResolution("8.8.8.8", "8.8.4.4:53");
// give each virtual user its own DNS cache, like real devices
// only effective with asyncNameResolution
mqtt
.asyncNameResolution()
.perUserNameResolution();// resolve the broker hostname with Gatling's non-blocking DNS resolver,
// using the system's DNS servers
mqtt.asyncNameResolution();
// force DNS servers, as "host" or "host:port"
mqtt.asyncNameResolution("8.8.8.8", "8.8.4.4:53");
// give each virtual user its own DNS cache, like real devices
// only effective with asyncNameResolution
mqtt
.asyncNameResolution()
.perUserNameResolution();// resolve the broker hostname with Gatling's non-blocking DNS resolver,
// using the system's DNS servers
mqtt.asyncNameResolution()
// force DNS servers, as "host" or "host:port"
mqtt.asyncNameResolution("8.8.8.8", "8.8.4.4:53")
// give each virtual user its own DNS cache, like real devices
// only effective with asyncNameResolution
mqtt
.asyncNameResolution()
.perUserNameResolution()// resolve the broker hostname with Gatling's non-blocking DNS resolver,
// using the system's DNS servers
mqtt.asyncNameResolution()
// force DNS servers, as "host" or "host:port"
mqtt.asyncNameResolution("8.8.8.8", "8.8.4.4:53")
// give each virtual user its own DNS cache, like real devices
// only effective with asyncNameResolution
mqtt
.asyncNameResolution()
.perUserNameResolutionConfigure acknowledgement timeouts and resends
Gatling resends the packets the broker doesn’t acknowledge within resendDelay. Use resendAttemptsMax to limit the number of resends, 3 by default.
When the broker still hasn’t acknowledged a packet one resend delay after the last resend, the publish, subscribe or unsubscribe fails.
Set resendAttemptsMax to 0 to disable resends and turn resendDelay into an acknowledgement timeout.
Use subscribeTimeout to define how long the broker can take to acknowledge a subscribe, 3 seconds by default.
When the timeout expires, the subscribe fails, but the connection stays open.
mqtt
// timeout for the broker to acknowledge a subscribe (default: 3 seconds)
.subscribeTimeout(Duration.ofSeconds(5))
// max number of resends of an unacknowledged packet (default: 3)
.resendAttemptsMax(5);mqtt
// timeout for the broker to acknowledge a subscribe (default: 3 seconds)
.subscribeTimeout({ amount: 5, unit: "seconds" })
// max number of resends of an unacknowledged packet (default: 3)
.resendAttemptsMax(5);mqtt
// timeout for the broker to acknowledge a subscribe (default: 3 seconds)
.subscribeTimeout(Duration.ofSeconds(5))
// max number of resends of an unacknowledged packet (default: 3)
.resendAttemptsMax(5)mqtt
// timeout for the broker to acknowledge a subscribe (default: 3 seconds)
.subscribeTimeout(5.seconds)
// max number of resends of an unacknowledged packet (default: 3)
.resendAttemptsMax(5)Configure MQTT 5 connection options
With MQTT 5, you can configure:
| Option | Description |
|---|---|
sessionExpiryInterval |
How long the broker keeps the session after the connection closes. When not set, the session expires with the connection, unless cleanSession is false, in which case it never expires, like with MQTT 3.1.1. |
connectUserProperty |
A user property to send in the CONNECT packet. |
publishUserProperty |
A user property to send with every PUBLISH packet, before the publish’s own user properties. |
You can call connectUserProperty and publishUserProperty several times, also with the same name.
Define names and values as Gatling Expression Language Strings or functions.
mqtt
.mqttVersion_5()
// how long the broker keeps the session after the connection closes
.sessionExpiryInterval(Duration.ofMinutes(10))
// user property sent in the CONNECT packet
.connectUserProperty("deviceType", "#{deviceType}")
// user property sent with every PUBLISH packet
.publishUserProperty("tenant", "#{tenant}");mqtt
.mqttVersion_5()
// how long the broker keeps the session after the connection closes
.sessionExpiryInterval({ amount: 10, unit: "minutes" })
// user property sent in the CONNECT packet
.connectUserProperty("deviceType", "#{deviceType}")
// user property sent with every PUBLISH packet
.publishUserProperty("tenant", "#{tenant}");mqtt
.mqttVersion_5()
// how long the broker keeps the session after the connection closes
.sessionExpiryInterval(Duration.ofMinutes(10))
// user property sent in the CONNECT packet
.connectUserProperty("deviceType", "#{deviceType}")
// user property sent with every PUBLISH packet
.publishUserProperty("tenant", "#{tenant}")mqtt
.mqttVersion_5
// how long the broker keeps the session after the connection closes
.sessionExpiryInterval(10.minutes)
// user property sent in the CONNECT packet
.connectUserProperty("deviceType", "#{deviceType}")
// user property sent with every PUBLISH packet
.publishUserProperty("tenant", "#{tenant}")Gatling also respects the limits the broker sends in its CONNACK packet:
- a publish fails without being sent when its QoS exceeds the broker’s Maximum QoS, when it’s retained and the broker doesn’t support retained messages, or when the packet exceeds the broker’s Maximum Packet Size
- Gatling applies the broker’s Server Keep Alive
Set MQTT 5 last will properties
With MQTT 5, the last will supports the same properties as publish, plus delayInterval, the time the broker waits after the connection is lost before publishing the last will.
mqtt
.mqttVersion_5()
.lastWill(
LastWill("#{willTopic}", StringBody("#{willMessage}"))
// wait 30 seconds after the connection is lost before publishing the last will
.delayInterval(Duration.ofSeconds(30))
// same properties as for publish
.contentType("text/plain")
.messageExpiryInterval(Duration.ofMinutes(5))
.userProperty("reason", "connection-lost")
);mqtt
.mqttVersion_5()
.lastWill(
LastWill("#{willTopic}", StringBody("#{willMessage}"))
// wait 30 seconds after the connection is lost before publishing the last will
.delayInterval({ amount: 30, unit: "seconds" })
// same properties as for publish
.contentType("text/plain")
.messageExpiryInterval({ amount: 5, unit: "minutes" })
.userProperty("reason", "connection-lost")
);mqtt
.mqttVersion_5()
.lastWill(
LastWill("#{willTopic}", StringBody("#{willMessage}"))
// wait 30 seconds after the connection is lost before publishing the last will
.delayInterval(Duration.ofSeconds(30))
// same properties as for publish
.contentType("text/plain")
.messageExpiryInterval(Duration.ofMinutes(5))
.userProperty("reason", "connection-lost")
)mqtt
.mqttVersion_5
.lastWill(
LastWill("#{willTopic}", StringBody("#{willMessage}"))
// wait 30 seconds after the connection is lost before publishing the last will
.delayInterval(30.seconds)
// same properties as for publish
.contentType("text/plain")
.messageExpiryInterval(5.minutes)
.userProperty("reason", "connection-lost")
)Request
Use the mqtt("requestName") method in order to create a MQTT request.
connect
Your virtual users first have to establish a connection.
mqtt("Connecting").connect();mqtt("Connecting").connect();mqtt("Connecting").connect()mqtt("Connecting").connectsubscribe
Use the subscribe method to subscribe to an MQTT topic:
mqtt("Subscribing")
.subscribe("#{myTopic}")
// optional, override default QoS
.qosAtMostOnce();mqtt("Subscribing").subscribe("#{myTopic}")
// optional, override default QoS
.qosAtMostOnce();mqtt("Subscribing").subscribe("#{myTopic}") // optional, override default QoS
.qosAtMostOnce()mqtt("Subscribing")
.subscribe("#{myTopic}")
// optional, override default QoS
.qosAtMostOnceSet MQTT 5 subscription options
With MQTT 5, set subscription options on subscribe. Gatling keeps them when it restores the subscriptions after a reconnect.
mqtt("Subscribing")
.subscribe("#{myTopic}")
// don't receive the messages this virtual user publishes
.noLocal()
// keep the retain flag of the forwarded messages
.retainAsPublished()
// receive the retained messages when subscribing (default)
.retainHandlingSendAtSubscribe()
// receive the retained messages only if the subscription doesn't exist yet
.retainHandlingSendAtNewSubscribe()
// don't receive the retained messages when subscribing
.retainHandlingDontSend();mqtt("Subscribing").subscribe("#{myTopic}")
// don't receive the messages this virtual user publishes
.noLocal()
// keep the retain flag of the forwarded messages
.retainAsPublished()
// receive the retained messages when subscribing (default)
.retainHandlingSendAtSubscribe()
// receive the retained messages only if the subscription doesn't exist yet
.retainHandlingSendAtNewSubscribe()
// don't receive the retained messages when subscribing
.retainHandlingDontSend();mqtt("Subscribing").subscribe("#{myTopic}")
// don't receive the messages this virtual user publishes
.noLocal()
// keep the retain flag of the forwarded messages
.retainAsPublished()
// receive the retained messages when subscribing (default)
.retainHandlingSendAtSubscribe()
// receive the retained messages only if the subscription doesn't exist yet
.retainHandlingSendAtNewSubscribe()
// don't receive the retained messages when subscribing
.retainHandlingDontSend()mqtt("Subscribing")
.subscribe("#{myTopic}")
// don't receive the messages this virtual user publishes
.noLocal
// keep the retain flag of the forwarded messages
.retainAsPublished
// receive the retained messages when subscribing (default)
.retainHandlingSendAtSubscribe
// receive the retained messages only if the subscription doesn't exist yet
.retainHandlingSendAtNewSubscribe
// don't receive the retained messages when subscribing
.retainHandlingDontSendTell subscriptions apart with Subscription Identifiers
With MQTT 5, use subscriptionIdentifier to set a Subscription Identifier between 1 and 268,435,455 on a subscription.
The broker adds it to the messages it forwards for this subscription.
When a subscribe with a Subscription Identifier has an await or expect, only the messages carrying this identifier match, which tells apart overlapping subscriptions.
Inbound messages expose their Subscription Identifiers, see Processing unmatched messages.
// await only matches the messages the broker forwards for this subscription
mqtt("Subscribing to all sensors")
.subscribe("sensors/#")
.subscriptionIdentifier(1)
.await(Duration.ofSeconds(1));
// the identifier can also be a Gatling Expression Language String or a function
mqtt("Subscribing to my sensor")
.subscribe("sensors/#{sensorId}")
.subscriptionIdentifier("#{subscriptionId}");// await only matches the messages the broker forwards for this subscription
mqtt("Subscribing to all sensors").subscribe("sensors/#")
.subscriptionIdentifier(1)
.await({ amount: 1, unit: "seconds" });
// the identifier can also be a Gatling Expression Language String or a function
mqtt("Subscribing to my sensor").subscribe("sensors/#{sensorId}")
.subscriptionIdentifier("#{subscriptionId}");// await only matches the messages the broker forwards for this subscription
mqtt("Subscribing to all sensors").subscribe("sensors/#")
.subscriptionIdentifier(1)
.await(Duration.ofSeconds(1))
// the identifier can also be a Gatling Expression Language String or a function
mqtt("Subscribing to my sensor").subscribe("sensors/#{sensorId}")
.subscriptionIdentifier("#{subscriptionId}")// await only matches the messages the broker forwards for this subscription
mqtt("Subscribing to all sensors")
.subscribe("sensors/#")
.subscriptionIdentifier(1)
.await(1.second)
// the identifier can also be a Gatling Expression Language String or a function
mqtt("Subscribing to my sensor")
.subscribe("sensors/#{sensorId}")
.subscriptionIdentifier("#{subscriptionId}")Use shared subscriptions
With MQTT 5, subscribe to a $share/<group>/<topic filter> topic to join a shared subscription: the broker spreads the messages among the subscribers of the group.
await and expect match the messages received on the topic filter, without the $share/<group>/ prefix.
A subscribe with noLocal on a shared subscription fails, instead of getting the connection closed by the broker.
// the broker spreads the messages of sensors/# among the members of the group
mqtt("Subscribing")
.subscribe("$share/my-group/sensors/#")
.expect(Duration.ofSeconds(1));// the broker spreads the messages of sensors/# among the members of the group
mqtt("Subscribing").subscribe("$share/my-group/sensors/#")
.expect({ amount: 1, unit: "seconds" });// the broker spreads the messages of sensors/# among the members of the group
mqtt("Subscribing").subscribe("\$share/my-group/sensors/#")
.expect(Duration.ofSeconds(1))// the broker spreads the messages of sensors/# among the members of the group
mqtt("Subscribing")
.subscribe("$share/my-group/sensors/#")
.expect(1.second)unsubscribe
Use the unsubscribe method to unsubscribe from an MQTT topic. Gatling logs the response once the broker acknowledges the UNSUBSCRIBE packet.
mqtt("Unsubscribing").unsubscribe("#{myTopic}");mqtt("Unsubscribing").unsubscribe("#{myTopic}");mqtt("Unsubscribing").unsubscribe("#{myTopic}")mqtt("Unsubscribing").unsubscribe("#{myTopic}")publish
Use the publish method to publish a message. You can use the same Body API as for HTTP request bodies:
mqtt("Publishing")
.publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"));mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"));mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"))mqtt("Publishing")
.publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"))Use retain to override the protocol’s retain flag for one publish:
mqtt("Publishing")
.publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"))
// override the protocol's retain flag
.retain(true);mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"))
// override the protocol's retain flag
.retain(true);mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"))
// override the protocol's retain flag
.retain(true)mqtt("Publishing")
.publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"))
// override the protocol's retain flag
.retain(true)Set MQTT 5 publish properties
With MQTT 5, set the following properties on publish:
| Property | Description |
|---|---|
userProperty |
A user property. Call it several times to add several user properties, also with the same name. |
contentType |
The content type of the payload. |
payloadFormatUtf8 |
Flag the payload as UTF-8 encoded text. Brokers may validate it, and refuse the message with PAYLOAD_FORMAT_INVALID otherwise. |
messageExpiryInterval |
How long the broker keeps the message for subscribers that haven’t received it yet. |
responseTopic |
The topic responders publish their response to. |
correlationData |
The Correlation Data, as a String encoded in UTF-8. |
correlationDataBytes |
The Correlation Data, as bytes. |
mqtt("Publishing")
.publish("#{myTopic}")
.message(StringBody("{\"temperature\": #{temperature}}"))
// add user properties, possibly several with the same name
.userProperty("sensorId", "#{sensorId}")
.userProperty("unit", "celsius")
.contentType("application/json")
// flag the payload as UTF-8 encoded text
.payloadFormatUtf8()
// how long the broker keeps the message for subscribers that haven't received it yet
.messageExpiryInterval(Duration.ofMinutes(1))
// where responders publish their response
.responseTopic("responses/#{id}")
// set the Correlation Data as a UTF-8 String
.correlationData("#{requestId}");
// set the Correlation Data as bytes
mqtt("Publishing")
.publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"))
.correlationDataBytes(session -> session.getString("requestId").getBytes(StandardCharsets.UTF_8));mqtt("Publishing").publish("#{myTopic}")
.message(StringBody('{"temperature": #{temperature}}'))
// add user properties, possibly several with the same name
.userProperty("sensorId", "#{sensorId}")
.userProperty("unit", "celsius")
.contentType("application/json")
// flag the payload as UTF-8 encoded text
.payloadFormatUtf8()
// how long the broker keeps the message for subscribers that haven't received it yet
.messageExpiryInterval({ amount: 1, unit: "minutes" })
// where responders publish their response
.responseTopic("responses/#{id}")
// set the Correlation Data as a UTF-8 String
.correlationData("#{requestId}");
// set the Correlation Data as bytes
mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"))
.correlationDataBytes((session) => session.get<number[]>("requestIdBytes"));mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("""{"temperature": #{temperature}}"""))
// add user properties, possibly several with the same name
.userProperty("sensorId", "#{sensorId}")
.userProperty("unit", "celsius")
.contentType("application/json")
// flag the payload as UTF-8 encoded text
.payloadFormatUtf8()
// how long the broker keeps the message for subscribers that haven't received it yet
.messageExpiryInterval(Duration.ofMinutes(1))
// where responders publish their response
.responseTopic("responses/#{id}")
// set the Correlation Data as a UTF-8 String
.correlationData("#{requestId}")
// set the Correlation Data as bytes
mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"))
.correlationDataBytes { session -> session.getString("requestId")!!.toByteArray(Charsets.UTF_8) }mqtt("Publishing")
.publish("#{myTopic}")
.message(StringBody("""{"temperature": #{temperature}}"""))
// add user properties, possibly several with the same name
.userProperty("sensorId", "#{sensorId}")
.userProperty("unit", "celsius")
.contentType("application/json")
// flag the payload as UTF-8 encoded text
.payloadFormatUtf8
// how long the broker keeps the message for subscribers that haven't received it yet
.messageExpiryInterval(1.minute)
// where responders publish their response
.responseTopic("responses/#{id}")
// set the Correlation Data as a UTF-8 String
.correlationData("#{requestId}")
// set the Correlation Data as bytes
mqtt("Publishing")
.publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"))
.correlationDataBytes(session => session("requestId").validate[String].map(_.getBytes(StandardCharsets.UTF_8)))Understand how Gatling handles broker refusals
Gatling marks requests as failed when the broker refuses them:
- subscribe, unsubscribe and publish fail when the broker answers with a failure reason code in SUBACK, UNSUBACK, PUBACK or PUBREC. With MQTT 3.1.1, a SUBACK with the 0x80 failure return code fails the subscribe.
- when the broker refuses the connection in CONNACK for a reason that a new attempt can’t fix, such as bad credentials, a client identifier the broker rejects, or a refused last will, Gatling doesn’t reconnect.
- when an MQTT 5 broker sends a DISCONNECT packet, Gatling logs the reason and closes the connection. It reconnects, except when the reason is
NOT_AUTHORIZEDorSESSION_TAKEN_OVER.
When Gatling reconnects and the broker doesn’t have a session for the client anymore, for example with cleanSession(true), Gatling subscribes again to the topics the virtual user subscribed to.
MQTT checks
You can define blocking checks with await and non-blocking checks with expect.
Those can be set right after subscribing, or after publishing.
After publishing, you can optionally define in which topic the expected message is received, and define check criteria to apply on the matching received message:
// subscribe and expect to receive a message within 100ms, without blocking flow
mqtt("Subscribing")
.subscribe("#{myTopic2}")
.expect(Duration.ofMillis(100));
// publish and await (block) until it receives a message withing 100ms
mqtt("Publishing")
.publish("#{myTopic}")
.message(StringBody("#{myPayload}"))
.await(Duration.ofMillis(100));
// optionally, define in which topic the expected message will be received
mqtt("Publishing")
.publish("#{myTopic}")
.message(StringBody("#{myPayload}"))
.await(Duration.ofMillis(100), "repub/#{myTopic}");
// optionally define check criteria to be applied on the matching received message
mqtt("Publishing")
.publish("#{myTopic}")
.message(StringBody("#{myPayload}"))
.await(Duration.ofMillis(100))
.check(jsonPath("$.error").notExists());// subscribe and expect to receive a message within 100ms, without blocking flow
mqtt("Subscribing").subscribe("#{myTopic2}")
.expect({ amount: 100, unit: "milliseconds" });
// publish and await (block) until it receives a message withing 100ms
mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myPayload}"))
.await({ amount: 100, unit: "milliseconds" });
// optionally, define in which topic the expected message will be received
mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myPayload}"))
.await({ amount: 100, unit: "milliseconds" }, "repub/#{myTopic}");
// optionally define check criteria to be applied on the matching received message
mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myPayload}"))
.await({ amount: 100, unit: "milliseconds" }, "repub/#{myTopic}")
.check(jsonPath("$.error").notExists());// subscribe and expect to receive a message within 100ms, without blocking flow
mqtt("Subscribing").subscribe("#{myTopic2}")
.expect(Duration.ofMillis(100))
// publish and wait (block) until it receives a message withing 100ms
mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myPayload}"))
.await(Duration.ofMillis(100))
// optionally, define in which topic the expected message will be received
mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myPayload}"))
.await(Duration.ofMillis(100), "repub/#{myTopic}")
// optionally define check criteria to be applied on the matching received message
mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myPayload}"))
.await(Duration.ofMillis(100))
.check(jsonPath("$.error").notExists())// subscribe and expect to receive a message within 100ms, without blocking flow
mqtt("Subscribing")
.subscribe("#{myTopic2}")
.expect(100.milliseconds)
// publish and await (block) until it receives a message withing 100ms
mqtt("Publishing")
.publish("#{myTopic}")
.message(StringBody("#{myPayload}"))
.await(100.milliseconds)
// optionally, define in which topic the expected message will be received
mqtt("Publishing")
.publish("#{myTopic}")
.message(StringBody("#{myPayload}"))
.await(100.milliseconds, "repub/#{myTopic}")
// optionally define check criteria to be applied on the matching received message
mqtt("Publishing")
.publish("#{myTopic}")
.message(StringBody("#{myPayload}"))
.await(100.milliseconds)
.check(jsonPath("$.error").notExists)You can use waitForMessages and block for all pending non-blocking checks:
mqtt.waitForMessages().timeout(Duration.ofMillis(100));mqtt.waitForMessages().timeout({ amount: 100, unit: "milliseconds" });mqtt.waitForMessages().timeout(Duration.ofMillis(100))mqtt.waitForMessages.timeout(100.milliseconds)Match topic filters with wildcards
The topic of subscribe, and the expected topic of publish, can be a topic filter with the + single level and # multi level wildcards.
await and expect then match the messages received on any topic matching the filter.
When a message matches several pending checks, Gatling picks the ones on the exact topic first, then the topic filters in the order the checks were registered.
// match the messages received on any topic under sensors/
mqtt("Subscribing")
.subscribe("sensors/#")
.await(Duration.ofSeconds(1));
// match the response on any topic matching the topic filter
mqtt("Publishing")
.publish("requests/#{deviceId}")
.message(StringBody("#{myPayload}"))
.await(Duration.ofSeconds(1), "responses/+/#{deviceId}");// match the messages received on any topic under sensors/
mqtt("Subscribing").subscribe("sensors/#")
.await({ amount: 1, unit: "seconds" });
// match the response on any topic matching the topic filter
mqtt("Publishing").publish("requests/#{deviceId}")
.message(StringBody("#{myPayload}"))
.await({ amount: 1, unit: "seconds" }, "responses/+/#{deviceId}");// match the messages received on any topic under sensors/
mqtt("Subscribing").subscribe("sensors/#")
.await(Duration.ofSeconds(1))
// match the response on any topic matching the topic filter
mqtt("Publishing").publish("requests/#{deviceId}")
.message(StringBody("#{myPayload}"))
.await(Duration.ofSeconds(1), "responses/+/#{deviceId}")// match the messages received on any topic under sensors/
mqtt("Subscribing")
.subscribe("sensors/#")
.await(1.second)
// match the response on any topic matching the topic filter
mqtt("Publishing")
.publish("requests/#{deviceId}")
.message(StringBody("#{myPayload}"))
.await(1.second, "responses/+/#{deviceId}")Correlate responses on the MQTT 5 Correlation Data
With MQTT 5, use correlateByCorrelationData instead of correlateBy to match responses with the publish expecting them on the Correlation Data property, which responders send back unchanged.
Every publish with await or expect must then set correlationData or correlationDataBytes, otherwise Gatling fails when building the simulation.
MqttProtocolBuilder protocol = mqtt
.mqttVersion_5()
.correlateByCorrelationData();
ChainBuilder requestResponse =
exec(
mqtt("Subscribing to responses").subscribe("responses/#{id}"),
mqtt("Requesting")
.publish("requests")
.message(StringBody("#{myPayload}"))
.responseTopic("responses/#{id}")
// mandatory with await or expect
.correlationData("#{requestId}")
.await(Duration.ofSeconds(1), "responses/#{id}")
);const protocol = mqtt
.mqttVersion_5()
.correlateByCorrelationData();
const requestResponse = exec(
mqtt("Subscribing to responses").subscribe("responses/#{id}"),
mqtt("Requesting").publish("requests")
.message(StringBody("#{myPayload}"))
.responseTopic("responses/#{id}")
// mandatory with await or expect
.correlationData("#{requestId}")
.await({ amount: 1, unit: "seconds" }, "responses/#{id}")
);val protocol = mqtt
.mqttVersion_5()
.correlateByCorrelationData()
val requestResponse =
exec(
mqtt("Subscribing to responses").subscribe("responses/#{id}"),
mqtt("Requesting").publish("requests")
.message(StringBody("#{myPayload}"))
.responseTopic("responses/#{id}")
// mandatory with await or expect
.correlationData("#{requestId}")
.await(Duration.ofSeconds(1), "responses/#{id}")
)val protocol = mqtt
.mqttVersion_5
.correlateByCorrelationData
val requestResponse =
exec(
mqtt("Subscribing to responses").subscribe("responses/#{id}"),
mqtt("Requesting")
.publish("requests")
.message(StringBody("#{myPayload}"))
.responseTopic("responses/#{id}")
// mandatory with await or expect
.correlationData("#{requestId}")
.await(1.second, "responses/#{id}")
)Processing unmatched messages
You can use processUnmatchedMessages to process inbound messages that haven’t been matched with a check and have been buffered.
By default, unmatched inbound messages are not buffered, you must enable this feature by setting the size of the buffer on the protocol with .unmatchedInboundMessageBufferSize(maxSize).
The buffer is reset when:
- sending an outbound message
- calling
processUnmatchedMessagesso we don’t present the same message twice
You can then pass your processing logic as a function.
The list of messages passed to this function is sorted in timestamp ascending (meaning older messages first).
It contains instances of type io.gatling.mqtt.action.MqttInboundMessage.
// store the unmatched messages in the Session
mqtt.processUnmatchedMessages("#{myTopic}", (messages, session) -> session.set("messages", messages));
// collect the last text message and store it in the Session
mqtt.processUnmatchedMessages(
"#{myTopic}",
(messages, session) ->
!messages.isEmpty()
? session.set("lastMessage", messages.get(messages.size() - 1).payloadUtf8String())
: session
);// store the unmatched messages in the Session
mqtt.processUnmatchedMessages("#{myTopic}", (messages, session) => session.set("messages", messages));
// collect the last text message and store it in the Session
mqtt.processUnmatchedMessages(
"#{myTopic}",
(messages, session) =>
messages.length > 0
? session.set("lastMessage", messages[messages.length - 1].payloadUtf8String())
: session
);// store the unmatched messages in the Session
mqtt.processUnmatchedMessages("#{myTopic}") { messages, session -> session.set("messages", messages) }
// collect the last text message and store it in the Session
mqtt.processUnmatchedMessages("#{myTopic}") { messages, session ->
messages
.map { m -> m.payloadUtf8String() }
.takeLast(1)
.fold(session) { _, lastMessage ->
session.set("lastMessage", lastMessage)
}
}// store the unmatched messages in the Session
mqtt.processUnmatchedMessages("#{myTopic}") {
(messages, session) => session.set("messages", messages)
}
// collect the last text message and store it in the Session
mqtt.processUnmatchedMessages("#{myTopic}") {
(messages, session) => {
val lastMessage = messages.reverseIterator.nextOption().map(_.payloadUtf8String)
lastMessage.fold(session)(m => session.set("lastMessage", m))
}
}The topic can be a topic filter with wildcards: Gatling then merges the messages of all the matching topics, in the order it received them.
With MQTT 5, subscriptionIdentifiers returns the Subscription Identifiers of the virtual user’s subscriptions the message matched, or an empty list if none of them has one.
// process the unmatched messages of all the topics matching a topic filter,
// and keep only the ones forwarded for the subscription with identifier 1
mqtt.processUnmatchedMessages(
"sensors/#",
(messages, session) ->
session.set(
"sensorMessages",
messages.stream()
.filter(m -> m.subscriptionIdentifiers().contains(1))
.map(MqttInboundMessage::payloadUtf8String)
.toList()
)
);// process the unmatched messages of all the topics matching a topic filter,
// and keep only the ones forwarded for the subscription with identifier 1
mqtt.processUnmatchedMessages(
"sensors/#",
(messages, session) =>
session.set(
"sensorMessages",
messages
.filter((m) => m.subscriptionIdentifiers().includes(1))
.map((m) => m.payloadUtf8String())
)
);// process the unmatched messages of all the topics matching a topic filter,
// and keep only the ones forwarded for the subscription with identifier 1
mqtt.processUnmatchedMessages("sensors/#") { messages, session ->
session.set(
"sensorMessages",
messages
.filter { m -> m.subscriptionIdentifiers().contains(1) }
.map { m -> m.payloadUtf8String() }
)
}// process the unmatched messages of all the topics matching a topic filter,
// and keep only the ones forwarded for the subscription with identifier 1
mqtt.processUnmatchedMessages("sensors/#") {
(messages, session) =>
session.set(
"sensorMessages",
messages
.filter(_.subscriptionIdentifiers.contains(1))
.map(_.payloadUtf8String)
)
}MQTT configuration
MQTT support honors the ssl and netty configurations from gatling.conf.
Example
public class MqttSample extends Simulation {
MqttProtocolBuilder mqttProtocol = mqtt
.broker("localhost", 1883)
.correlateBy(jsonPath("$.correlationId"));
ScenarioBuilder scn = scenario("MQTT Test")
.feed(csv("topics-and-payloads.csv"))
.exec(mqtt("Connecting").connect())
.exec(mqtt("Subscribing").subscribe("#{myTopic}"))
.exec(mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"))
.expect(Duration.ofMillis(100)).check(jsonPath("$.error").notExists()));
{
setUp(scn.injectOpen(rampUsersPerSec(10).to(1000).during(60)))
.protocols(mqttProtocol);
}
}export default simulation((setUp) => {
const mqttProtocol = mqtt
.broker("localhost", 1883)
.correlateBy(jsonPath("$.correlationId"));
const scn = scenario("MQTT Test")
.feed(csv("topics-and-payloads.csv"))
.exec(mqtt("Connecting").connect())
.exec(mqtt("Subscribing").subscribe("#{myTopic}"))
.exec(mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"))
.expect({ amount: 100, unit: "milliseconds" })
.check(jsonPath("$.error").notExists()));
setUp(scn.injectOpen(rampUsersPerSec(10).to(1000).during(60)))
.protocols(mqttProtocol);
});class MqttSample : Simulation() {
val mqttProtocol = mqtt
.broker("localhost", 1883)
.correlateBy(jsonPath("$.correlationId"))
val scn = scenario("MQTT Test")
.feed(csv("topics-and-payloads.csv"))
.exec(mqtt("Connecting").connect())
.exec(mqtt("Subscribing").subscribe("#{myTopic}"))
.exec(mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"))
.expect(Duration.ofMillis(100)).check(jsonPath("$.error").notExists()))
init {
setUp(scn.injectOpen(rampUsersPerSec(10.0).to(1000.0).during(60)))
.protocols(mqttProtocol)
}
}class MqttSample extends Simulation {
val mqttProtocol = mqtt
.broker("localhost", 1883)
.correlateBy(jsonPath("$.correlationId"))
val scn = scenario("MQTT Test")
.feed(csv("topics-and-payloads.csv"))
.exec(mqtt("Connecting").connect)
.exec(mqtt("Subscribing").subscribe("#{myTopic}"))
.exec(mqtt("Publishing").publish("#{myTopic}")
.message(StringBody("#{myTextPayload}"))
.expect(100.milliseconds).check(jsonPath("$.error").notExists))
setUp(scn.inject(rampUsersPerSec(10) to 1000 during (60)))
.protocols(mqttProtocol)
}