Featured image of post SpringBoot开发中的一些小细节(十四)事件监听的使用

SpringBoot开发中的一些小细节(十四)事件监听的使用

背景

最近在做同步先关的工作,为了提升同步任务的处理效率,减少频繁的mongo数据库查询,因此需要将一些数据统一查询出来,在内存中进行处理。

解决方式

在任务执行的之前,就需要将相关的数据查询出来,如何实现呢?使用一个@EventListener进行ApplicationReadyEvent时间的监听,就能在应用启动之后,进行相应的操作

@EventListener(classes = {ApplicationReadyEvent.class})
public void initialMap() {
    if (CollectionUtils.isEmpty(ridMobileMap)) {
        List<UserRecord> all = entranceUserRecordRepo.findAll();
        ridMobileMap = all.stream().filter(userRecord -> StringUtils.isNotEmpty(userRecord.getMobileNo())).collect(Collectors.toMap(UserRecord::getRid, UserRecord::getMobileNo));
    }
}

More

Application

spring application,一般就是spring boot项目中的 Application这个类

@SpringBootApplication
@EnableConfigurationProperties
@EnableAutoConfiguration(exclude = {DruidDataSourceAutoConfigure.class, DataSourceAutoConfiguration.class, RedisAutoConfiguration.class})
@EnableScheduling
@EnableFeignClients(basePackages = {""})
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableCircuitBreaker
@EnableLdapRepositories
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    LdapTemplate getLdapTemplate(ContextSource contextSource) {
        LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
        ldapTemplate.setIgnorePartialResultException(true);
        return ldapTemplate;
    }
}

在这个当中,我们可以设置很多配置,比如排除掉一些自动配置、设置feignClient的扫描路径等等操作。

Spring Boot详细生命周期介绍

自定义事件和监听

在不同的Service当中的时候,两个service的职责差别很大,但是A会调用B的方法,或者在A中个别服务完成之后,我们需要通知B中的个别方法开始执行。(观察者模式的一种实现)

自定义event

public class ObjectALifecycleEvent extends ApplicationEvent {

    private ObjectA objectA;

    /**
     * Create a new ApplicationEvent.
     *
     * @param source the object on which the event initially occurred (never {@code null})
     */
    public ObjectALifecycleEvent(Object source) {
        super(source);
        if (source instanceof ObjectA) {
            this.objectA = (ObjectA) source;
        }
    }

    public ObjectA getObjectA() {
        return objectA;
    }

}

自定义listener


@Component
@Slf4j
@Data
public class PolicyUpdater implements ApplicationListener<ObjectALifecycleEvent> {

 
    @Override
    public void onApplicationEvent(@NotNull ObjectALifecycleEvent event) {
        if (event instanceof ObjectABeforeScheduleEvent) {
            updatePolicyBeforeTaskSchedule((ObjectABeforeScheduleEvent) event);
        }
        if (event instanceof ObjectAFinishEvent) {
            updatePolicyWhenTaskFinish((ObjectAFinishEvent) event);
        }
    }
    
}
Licensed under CC BY-NC-SA 4.0
Owner Rainbowly
Total [] user views [] site views [] page views
Built with Hugo
主题 StackJimmy 设计