美文网首页
springboot+Event自定义事件模式简单版本

springboot+Event自定义事件模式简单版本

作者: 楼兰King | 来源:发表于2021-03-14 21:23 被阅读0次
不多说,直接上代码,简易版本,只是搭个简单模板
import org.springframework.context.ApplicationEvent;

public class KingEvent extends ApplicationEvent{
    //接收消息
    private String message;
    public KingEvent(String  msg) {
        super(msg);
        this.message=msg;
    }

    public String getMessage() {
        return message;
    }
}
时间监听类,注意,此处我使用的是异步方式
@Component
public class KingEventListener implements ApplicationListener<KingEvent> {
    @Async
    @Override
    public void onApplicationEvent(KingEvent kingEvent) {
        System.out.println("监听到事件"+kingEvent.getMessage());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss");
        String day=dateFormat.format(System.currentTimeMillis());
        System.out.println("当前时间:"+day);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("结束时间"+dateFormat.format(System.currentTimeMillis()));
    }
}
main方法测试
import net.sppan.base.eventCofig.KingEvent;
import net.sppan.base.eventCofig.KingEventListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class jiantingshijian {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(KingEventListener.class);
        KingEventListener listener= (KingEventListener) context.getBean(KingEventListener.class);
        System.out.println(listener.getClass());
        String msg="数值:";
        for(int i=0;i<10;i++){
            KingEvent event=new KingEvent(msg+i);
            listener.onApplicationEvent(event);
        }
    }
}

相关文章

网友评论

      本文标题:springboot+Event自定义事件模式简单版本

      本文链接:https://www.haomeiwen.com/subject/gbpccltx.html