How to start a process in spring-boot after injecting all the Beans and before you start listening to external events?

Asked

Viewed 351 times

1

I am creating an application in Spring-Boot that for me is critical she recover her previous processing point before to start receiving new requests.

For such, I have a table called PROCESSOS which holds a unique ID, its processing stage (queued, processing, completed, etc.), a pointer to where the data is being processed and other information not relevant to this issue.

To retrieve the processes that stopped in the middle of the way, I make the following query in the method List<Integer> recuperaBreakpoint():

SELECT id, 1 as type
FROM PROCESSOS
WHERE estagio_id != 'QUEUED' AND
    (estagio_id NOT LIKE 'FINISHED%' COLLATE NOCASE AND
    estagio_id NOT LIKE 'FAILED%' COLLATE NOCASE AND
    estagio_id NOT LIKE 'CANCELED%' COLLATE NOCASE)
UNION ALL
SELECT id, 2 as type 
FROM PROCESSOS  WHERE estagio_id = 'QUEUED'
ORDER BY type, id

And she returns to me what I want in the order I want:

  • return contains all unfinished/canceled/failed processes
  • prioritize in return who has already started some processing
  • only then do I put the lawsuits that were just lined up (QUEUED), but have not undergone any proceedings yet

In theory, after recovering these processes, it would only be to delegate to some available thread executor (or put in the process pool to be executed, in case there are no available executors). I do it through function void executaProcesso(int idProcesso), who will be in charge of delegating to exeutors/line up the requisitions perfectly.

The point is:

  • How, in Spring-Boot, I do to rescue these values and continue the process at the beginning of the application but before starting to answer external requests?
  • In other words, how to do recuperaBreakpoint().stream().forEachOrdered(this::executaProcesso) as soon as Spring-Boot is ready to run?

1 answer

2


Fala Jefferson,

You can accomplish this using Annotation @Eventlistener, it acts as Systener to execute certain method depending on the generated boot event.

The events derive from Applicationevent, may be used Springapplicationevent or Applicationcontextevent

Just put Annotation in the method and indicate the event where you would like to run the code:

@EventListener(ContextRefreshedEvent.class)
public void warmup() {
    System.out.println("Código executado logo após a aplicação ser startada");
}

I recommend you use the event Contextrefreshedevent because it runs before the application starts accepting requests (the requests are accepted after the issue of the event Applicationreadyevent).

  • 1

    I was about to answer something close to that, but I forgot. Then came his answer, considerably more grounded than I had in mind. Thank you very much for responding, and thank you in particular for the references

Browser other questions tagged

You are not signed in. Login or sign up in order to post.