@Scheduled 从控制器

@Scheduled from a Controller

我有一个 Spring-Boot 应用程序。使用这个抽象控制器

public abstract class ElCorDeLaCiutatController {
     static Double price = 0.0;     

     @Autowired
     PriceService priceService;

     @Scheduled(fixedRate = 1000 )
     private void updatePrice() throws DataAccessException, SQLException, ClientProtocolException, IOException {        
        price = getPrice();
     }
}

我想每秒更新一次价格,因为价格是所有控制器共享的公共值,但我看到这个方法每秒被调用大约 14 次...

也许对于扩展这个抽象控制器的所有控制器?

有没有办法避免这种情况?

我会将价格和时间表放在一个单独的 bean 中,并将其作为 ElCorDeLaCiutatController 的静态成员进行引用。

从 class 扩展可能会导致问题。还有一个像这样的静态字段来共享 classes 之间的值并不是最好的。

我认为更好的方法是将价格转移到价格服务。它无论如何都是一个静态值,所以它对所有控制器都是一样的。只需将其移动到服务并将计划任务移动到那里即可。让服务处理该价格(以及业务逻辑的所有其他部分),并在需要时在控制器中获取当前值。你也分开保持不同层的不同目的。

类似于:

class PriceService{

Double price = 0.0; 

getCurrentPrice(){
  return price;
}

@Scheduled
updatePrice(){
.. do something here
}

}

并且在控制器中,当您需要当前价格时,您只需使用注入服务中的 priceService.getCurrentPrice();,无需任何静态字段,也无需在控制器中维护状态