Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@async vs message queue difference

I have a spring boot project, deploying in two servers and using nginx. One method in the project will do:

  1. set some key-values in redis

  2. insert something in db

After 1, I want to do 2 in async way.

One solution is to let doDB() be a springboot @async method:

Class A {
    public void ***() {
        doRedis() // 1.set some key-values in redis
        doDB() // 2.insert something in db
    }
}

Class B {
    @async
    doDB()
}

Another solution is to send message to MQ:

Class A {
    public void ***() {
        doRedis() // 1.set some key-values in redis
        sendMessage() 
    }
}

Class B {
    onMessage(){
        doDB()
    }
}

If Class A and B are both in the spring boot project, just deploying this project in two servers. I think using @async is enough, there is no need to use MQ to achieve the async way because there is no difference between server one to do Class B doDB() and server two to do Class B doDB(). If class B is in another project, then using MQ is good because it's decoupling for project one doing redis work and project two doing db work.

Is it right? Thanks!

like image 319
magangxu Avatar asked Dec 06 '25 10:12

magangxu


1 Answers

Basically, you are right, if it is going to be in the same application within the same server, no need for MQ because async is already has a queue. But there are some key points you should be decided on even if in the same application

  1. if you care about ordering message queue is more meaningful, you can use async in this case too but you have to configure the thread pool to use only one thread to process async

  2. if you care about losing messages and if some bad things happen before processing messages, you should use an MQ that saves messages to the disk or somewhere to process the rest of the messages later on

  3. if your application gets a lot of requests and you did not carefully set threads in the async thread pool, you could get overflow errors or other problems with using machine resources

Choose within capabilities within your application, do not over-engineer from day one, you spin up from what you have and what you already tested

like image 199
Sahin Avatar answered Dec 07 '25 23:12

Sahin