Implementar el oyente basado en la interfaz de extensión Spring

Extendiendo Spring para implementar oyentes

La implementación es muy simple, solo necesita definir una clase para implementar la interfaz ApplicationListener y especificar el tipo genérico (tipo de evento monitoreado), reescribir el método onApplicationEvent en él y solo activar el tipo de evento actual ejecutará el método en él , y luego entréguelo al contenedor Spring IOC para su procesamiento.

Escenas a utilizar:

    /**
     * 此处的应用场景, 在维护老项目的时候加入了 redis 对数据进行缓存处理, 由于项目所有的数据都存储在 MySQL 中, 
     * 所以需要将数据库中的数据迁移到 redis 缓存中进行存储, 那么什么时候迁移数据呢, 在服务启动的时候就同步数据, 
     * 那么怎么在 spring 容器启动的时候触发数据同步呢, 学过前端的小伙伴立马就想到了时间监听器, 不错! 我们后端的小伙伴
     * 也说 java web 不是有三大组件之一的 Listener 监听器吗, 确实, 但是此处是通过实现 Spring 的 ApplicationContentListenr 
     * 拓展监听器的接口, 来完成容器已启动就立马触发数据同步.
     */

Spring proporciona los siguientes cinco eventos estándar:

  • Evento de actualización de contexto (ContextRefreshedEvent): se desencadena cuando se llama al método refresh() en la interfaz ConfigurableApplicationContext.
  • Evento de inicio de contexto (ContextStartedEvent): este evento se activa cuando el contenedor llama al método Start() de ConfigurableApplicationContext para iniciar/reiniciar el contenedor.
  • Evento de detención de contexto (ContextStoppedEvent): este evento se activa cuando el contenedor llama al método Stop() de ConfigurableApplicationContext para detener el contenedor.
  • Evento cerrado de contexto (ContextClosedEvent): este evento se desencadena cuando se cierra ApplicationContext. Cuando se cierra un contenedor, se destruyen todos los beans singleton que administra.
  • Evento de solicitud manejada (RequestHandledEvent): en una aplicación web, este evento se activa cuando finaliza una solicitud http (solicitud).

Si un bean implementa la interfaz ApplicationListener, se notifica automáticamente al bean cuando se publica un ApplicationEvent.

Defina el oyente e implemente la interfaz: ApplicationListener

/**
 * 攻略文章统计初始化监听器
 * 在 spring 容器自动成功后执行
 * 负责将 MySQL 中的数据初始化到 Redis 中
 */
@Component
public class StrategyStatDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    
    

    public static final Logger log = LoggerFactory.getLogger("StrategyStatDataInitListener");

    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IRedisService<KeyPrefix, Object> redisService;

     //当spring容器启动/初始化完成之后马上执行
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
    
    
        log.info("--------------------文章统计初始化开始--------------------");
        int count = 0;
        // 1. 查询所有的文章
        List<Strategy> strategyList = strategyService.list();
        for (Strategy strategy : strategyList) {
    
    
           // 2. 遍历所有的文章, 是否在 redis 中存在
           Boolean exists = redisService.exists(ArticleRedisPrefix.STRATEGIES_STAT_PREFIX, String.valueOf(strategy.getId()));
           if (! exists) {
    
    
               // 3. 如果不存在, 将其存入 redis, 如果存在则不更新
               Map<String, Object> map = new HashMap<>();
               map.put(ArticleStatVo.FAVOR_NUM, strategy.getFavornum());
               map.put(ArticleStatVo.REPLY_NUM, strategy.getReplynum());
               map.put(ArticleStatVo.SHARE_NUM, strategy.getSharenum());
               map.put(ArticleStatVo.THUMBSUP_NUM, strategy.getThumbsupnum());
               map.put(ArticleStatVo.VIEW_NUM, strategy.getViewnum());

               // 一次性的将整个 map put 到 redis 的 hash 中
               redisService.hputAll(ArticleRedisPrefix.STRATEGIES_STAT_PREFIX, map, String.valueOf(strategy.getId()));
               count++;
           }
        }
        log.info("--------------------文章初始化完成, 初始化数量: {}--------------------", count);
    }
}

``

Supongo que te gusta

Origin blog.csdn.net/weixin_49137820/article/details/128538510
Recomendado
Clasificación