观察者模式和SpringBoot @Service

Observer Pattern and SpringBoot @Service

谁能帮助我如何处理观察者模式和SpringBoot @Service?

假设我有 class:

WeatherStation[temperature, humidity, windSpeed ...] - subject (observable)

我可以有很多这样的 classes,我需要更新数据库中的数据,所以当温度变化时,我需要在正确的 WeatherStation 下将其记录到数据库中。

我提出了三个解决方案,第一个是:

Create class WeatherStationObserver which would have reference to WeatherStationRepository and I would register one WeatherStationObserver for one WeatherStation and the WeatherStationObserver would save the data to database (this is similar how I have it implemented right now) but there are some caviats. For example I can not @Autowire to WeatherStationObserver and I can not make the methods @Transactional ...

第二个想法是:

Create WeatherStationUpdateService which would be called from WeatherStationObserver. I don't like this because the WeatherStationObserver serves here only to call the WeatherStationUpdateService.

第三个想法:

Make the service an observer and register it for each WeatherStation but I am not sure if the service should not be called only from outside and if it is good practise service to behave as observer.

有人可以帮我吗?

将气象站与其相应的 ID 存储在数据库中。

每个人都有一个“最后轮询时间”。

有一个 @Scheduled and @Transactional 任务拉取最近(x 秒内)未被轮询的 20 个站的页面并查询它们的数据,处理它并坚持更新“最后一次轮询于" 对于每个。

如果您必须将它们都放在一起,然后进行 OPC UA 数据提取,当每个数据返回时,只需将数据放入队列(例如 ActiveMQ),然后 @JmsListener将处理该队列,一次拉动进行持久化(不重击数据库)。