Asynchronous Programming by Using Spring Events
In this article, i will implement an API that uses Spring Events. At the end of the article, we will have a ecosystem like this. Please don’t waste your time with understanding the business logic in codes. Just focus on the usage of Spring Events.
Now let’s start with creating the Spring Boot project. I used Spring Initializr for that but u can create a maven project basicly and add required dependencies. So, here is the dependencies that we will use in our project.
First we need tables to store data in H2 Database. Let’s create them.
We will specify the automatic creation of tables in the application.properties.
As i mentioned, this projects will be an REST API. So we need some rest controllers to handle http request, and DTOs to map request bodies.
We will connect to the database via repositories.
From this point, we need to make some configurations about Spring Event Bus and create the events that we will listen later.
Finally we can create our services to handle some basic database operations like decreasing the quantity of product, add product into the basket, create a basket, etc.
In service part, we raised the events. Now we can listen them and make any operation we want. For example, let’s simulate some cases like sending an e-mail when product price changed. etc. Here is the listeners:
Almost we implemented everything we need. Before testing the API, we should set boilerplate properties that we need.
Now, go to the project directory and run the command from terminal.
mvn spring-boot:run
For testing the API, you can run these commands.
curl --location --request POST 'http://localhost:8080/product' --header 'Content-Type: application/json' --data-raw '{"name": "T-shirt", "price": 46.3, "quantity": 100}'curl --location --request POST 'http://localhost:8080/product' --header 'Content-Type: application/json' --data-raw '{"name": "Sneaker", "price": 350.0, "quantity": 50}'curl --location --request POST 'http://localhost:8080/product' --header 'Content-Type: application/json' --data-raw '{"name": "Laptop", "price": 2500.0, "quantity": 200}'
curl --location --request POST 'http://localhost:8080/basket' --header 'Content-Type: application/json' --data-raw '{"productIds": [1,2]}'curl --location --request POST 'http://localhost:8080/basket' --header 'Content-Type: application/json' --data-raw '{"productIds": [1,2,3]}'curl --location --request POST 'http://localhost:8080/basket/1' --header 'Content-Type: application/json' --data-raw '{"productId": 3}'
curl --location --request POST 'http://localhost:8080/basket/1/confirm'curl --location --request PATCH 'http://localhost:8080/product/1' --header 'Content-Type: application/json' --data-raw '{"price": 150}'
Here is the terminal:
Thank you for reading the article. I know it’s not a very illustrative article. But still I wrote it as a note to myself and small contribution for you. You can see the source codes from here. HAVE A NICE DAY :))