Spring trigger/notify explicitly a Scheduled method

元气小坏坏 提交于 2019-12-24 07:38:39

问题


Transactions likes sales and purchase that are created via REST

@Component
@Path("txns")
public class Transaction {

 @Path("/purchases")
 public Response postPurchaseTrnsaction(Transaction txn) {
    // persistence takes place here
 }

 @Path("/sales")
 public Response postSalesTrnsaction(Transaction txn) {
    // persistence takes place here
 }     
}

There is a separate Background Inventory process that updates Inventory of SKUs which are sold or purchased from the above trnsactions.

public class InventoryProcessor {

  @Scheduled(fixedRate = 900000,initialDelay = 3000) // 15 mins
  @Transactional
  public void doInventory() {
    // open Transactions, update inventory records
  }

}

This process runs every 15 mins. However, whenever a new transactions arrive, need to trigger or notify the InventoryProcessor doInventory method explicitly to perform inventory immediately.

Is there a option in spring.


回答1:


Can you inject InventoryProcessor into Transaction and call the method programatically? Or wrap the call in another method marked @Async if it needs to be done asynchronously.

@Component
@Path("txns")
public class Transaction {

 @Inject
 private InventoryProcessor inventoryProcessor

 @Path("/purchases")
 public Response postPurchaseTrnsaction(Transaction txn) {
    // persistence takes place here

    inventoryProcessor.doInventory();
 }

 @Path("/sales")
 public Response postSalesTrnsaction(Transaction txn) {
    // persistence takes place here
 }     
}



回答2:


You can implement observer pattern using ApplicationEventPulistherAware in your inventory Processor and have your transaction functions publish the custom events through an implementation of ApplicationEventPublisher



来源:https://stackoverflow.com/questions/42791023/spring-trigger-notify-explicitly-a-scheduled-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!