Implement the listener based on the Spring extension interface

Extending Spring to implement listeners

The implementation is very simple. You only need to define a class to implement the ApplicationListener interface, and specify the generic type (the event type to monitor), and rewrite the onApplicationEvent method inside. Only when the current event type is triggered, the method inside will be executed, and then handed over to the Spring IOC container for processing manage.

scenes to be used:

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

Spring provides the following five standard events:

  • Context update event (ContextRefreshedEvent): It is triggered when the refresh() method in the ConfigurableApplicationContext interface is called.
  • Context Start Event (ContextStartedEvent): This event is triggered when the container calls the Start() method of ConfigurableApplicationContext to start/restart the container
  • Context stop event (ContextStoppedEvent): This event is triggered when the container calls the Stop() method of ConfigurableApplicationContext to stop the container.
  • Context closed event (ContextClosedEvent): This event is triggered when the ApplicationContext is closed. When a container is shut down, all singleton beans it manages are destroyed.
  • Request Handled Event (RequestHandledEvent): In a web application, this event is triggered when an http request (request) ends.

If a bean implements the ApplicationListener interface, the bean is automatically notified when an ApplicationEvent is published.

Define the listener and implement the interface: 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);
    }
}

``

Guess you like

Origin blog.csdn.net/weixin_49137820/article/details/128538510