Realtime Data with MariaDB and Websocket [Part 1]
Goal
We are going to learn and build a service that serves real-time data with MariaDB as the underlying database.
Why?
User expectations are increasing, and real-time data has become mandatory for a great web application. In this article, we are going to see possible options to build real-time data that serves data with MariaDB as our database.
There are a lot of software that offers this kind of real-time feature, one of them is debezium another is supabase, but we are going to create it our own.
Pre-requisite
- java17
- mariadb
How?
There are multiple options to build real-time data, one of them is polling the table that users registered to, for example, if a user subscribes to table user_profile
there will be a service that regularly queries into that table and check if the table has been modified.
It’s not the most efficient method, but it will get the job done.
Another alternative is by monitoring a binlog file (binary log) file.
The term “binary log file” generally denotes an individual numbered file containing database events. The term “binary log” collectively denotes the set of numbered binary log files plus the index file.
In short, it is a collection of events that are happening in a database.
These log files are mostly used for replication sources and we are using it to listen to any changes that is happening in our database.
We are going to use 2 main libraries.
- mysql-bin-log-connector to parse event from binlog file.
- JSqlParser to parse the query we retrieve from binlog.
Monitoring binlog file
A MariaDB uses mixed-logging as its default binary format.
To enable it add --log-bin --log-basename=[your_logfile_name]
When the database starts there should be a file in your data directory called your_logfile_name-bin.000001
Part 1, The Service
In this part, we are going to learn how to build a service that listens to the changes in the database and parses it.
You can get the full code in this repo
First thing first, we are going to start our project, in this example, I am going to start a micronaut project because later we are going to use its web socket feature to streamline the data.
But you can use a simple gradle project or event you can build the project from scratch.
1 | import java.io.IOException; |
When you start it, it should give you this log.
1 | May 12, 2024 9:07:30 PM com.github.shyiko.mysql.binlog.BinaryLogClient connect |
Now try to modify any table by doing either INSERT
, UPDATE
or DELETE
.
If you see this line.
1 | {queryType=INSERT, tableName=`user`} |
Congratulations, you’ve successfully listened to your database changes.
In the next part, we are going to fetch the modified table and streamline it using web socket.
To be continued.