立即试用 商务报价
社区版
指南 > Tutorials > Basics > Using queues for synchronization

本页目录

Using queues for synchronization

Use case

Let’s assume you need to implement the “counter” logic using ThingsBoard Rule Engine. Basically, message processing is executed asynchronously inside the Rule Nodes. Due to this fact, in most cases, the logic “get present counter value -> add new counter value -> save counter value” leads to the incorrect final result (unlike your expectations) due to the race condition issue. It is a well-known problem for all who dealt with multi-threading programming. You can refer to this article which nicely describes the problem and the existed solutions. Starting the ThingsBoard v2.5 this processing issue could be solved using special configurable queues.

In this tutorial, we will configure ThingsBoard Rule Engine to use queue with sequential by originator message submit strategy. Although this scenario is fictional, you will learn how to work with the queue to allow processing messages in sequential order and use this knowledge in real-life applications.

Prerequisites

We assume you have completed the following guides and reviewed the articles listed below:

In addition, you need to have at least one device provisioned in your environment.

Step 1: Creating the Rule Chain

image

We will add two generator nodes that will generate seven messages each. First generator will produce a message with the counter value of 101. Second - with the value of 10. So the result should be 777.

image image

Both messages will be put into the queue with the name “SequentialByOriginator”. It uses the message submit strategy called “SEQUENTIAL_WITHIN_ORIGINATOR” (please, refer to configuration guide for more details) which means that the subsequent message will start being processed when the preceding message is acknowledged (is processed and deleted from the queue) based on the originator.

image

We will get the present “counter” value using “Originator Attributes” node. image

The calculations will be done using “Counter Script” node.

image

The last step will be to save the new counter value using “Save Attributes” node.

Step 2: Validation the Rule Chain logic

Let’s check that our logic is correct by saving the Rule Chain. The generators will automatically produce 14 messages:

image

The final counter value that is persisted for a device is:

image

That means that our logic works correctly.

TL;DR

Download and import attached json file with a rule chain from this tutorial. Don’t forget to populate the Generator nodes with your specific device.

Next steps

  • 入门指南 - 快速学习ThingsBoard相关功能。

  • 安装指南 - 学习如何在各种操作系统上安装ThingsBoard。

  • 连接设备 - 学习如何根据你的连接方式或解决方案连接设备。

  • 可 视 化 - 学习如何配置复杂的ThingsBoard仪表板说明。

  • 数据分析 - 学习如何使用规则引擎执行基本的分析任务。

  • 硬件样品 - 学习如何将各种硬件平台连接到ThingsBoard。

  • 高级功能 - 学习高级ThingsBoard功能。

  • 开发指南 - 学习ThingsBoard中的贡献和开发。