How to use CompletableFuture Class after reading from a queue and save it into database or write to a file ?
Let’s say you have a need to read from a very high volume queue and there is a need of having that volume at low. Also after reading these payload there is a need to save it to data source or write to a file. Well using CompletableFuture’s asynchronous process we could read and then write at the same time.
@Override @JmsListener(containerFactory = "mqContainer", destination = "${your-destination-name-to-read-from}") public void processMessage(Message<?> somePayload) throws IOException { String message =somePayload.getPayload(); //Saving payload in linkedlist List<String> readPayload = new LinkedList<>(); readPayload.add(message); //Read payload of some objectType //Using an asynchronous way of reading and writing to a file or db CompletableFuture.supplyAsync(() -> { List<String> yourObjectList = new LinkedList<>( readPayload); for (YourObject yo : yourObjectList) { try { writeToFileOrWriteToDbLogic(yo); } catch (Exception e) { //Based on your need you can catch then throw , or log. } } return null; }); }
Let us know if this works below.