Home > Java > javaTutorial > How to start a listening thread to perform tasks in springboot

How to start a listening thread to perform tasks in springboot

WBOY
Release: 2023-05-21 20:28:12
forward
1281 people have browsed it

    springboot starts a listening thread to perform tasks

    public class StartApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    
        @Override
        public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
            ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
            ApplicationContext parent = applicationContext.getParent();
            if (parent == null) {
                CacheManager cacheManager = applicationContext.getBean(CacheManager.class);
                Cache cache = cacheManager.getCache(MsConstants.NODE_CACHE_NAME);
               new Thread(new Runnable() {
                   @Override
                   public void run() {
                      //代码
                     
                   }
               }).start();
            }
        }
    Copy after login
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(FigureServerApplication.class);
        app.addListeners(new StartApplicationListener());
        app.run(args);
    }
    Copy after login

    Creation process of listening events in springboot

    In the Spring Boot project, you can Use the annotation @Async to implement asynchronous processing, and event listening has two methods: synchronous and asynchronous.

    General steps of events

    • 1: Define an event.

    • 2: Create a listener.

    • 3: Make sure the listener is inside the container.

    • 4: Publish the event for testing.

    Without further ado, let’s briefly describe the demos of several different methods.

    First, we create a springboot project.

    First type

    1: Define an event and need to inherit ApplicationEvent

    public class MyEvent extends ApplicationEvent {
        public MyEvent(Object source) {
            super(source);
            System.out.println("我是一个事件,目前在事件的构造器内");
        }
    }
    Copy after login

    2: Create a listener. Directly implement the ApplicationListener interface and rewrite the onApplicationEvent method.

    public class MyEventListener implements ApplicationListener<MyEvent> {
        @Override
        public void onApplicationEvent(MyEvent event) {
            System.out.println("现在开始执行监听器中的内容,我是直接实现ApplicationListener接口的方式进行的");
            System.out.println("event.getSource() = " + event.getSource());
        }
    }
    Copy after login

    3: Manually add the listener to the application container and publish the event.

    @SpringBootApplication
    public class EventTestApplication {
        public static void main(String[] args) {
    //        SpringApplication.run(EventTestApplication.class, args);
            //第一种:自己手动将监听器添加到application中
            SpringApplication application = new SpringApplication(EventTestApplication.class);
            //添加监听器
            application.addListeners(new MyEventListener());
            ConfigurableApplicationContext context = application.run(args);
            //进行发布事件
            context.publishEvent(new MyEvent("Event数据源"));
            context.close();
        }
    }
    Copy after login

    4: Start the main startup class and perform printing tests.

    Second type

    1: Same as the first type 1

    2: Create a listener.

    /**
     *第二种:打上Compoent注解,  将事件监听器自动加入到应用容器中
     * 这种方式不需要手动加入到容器中。
     * */
    @Component
    public class MyEventListener2 implements ApplicationListener<MyEvent> {
        @Override
        public void onApplicationEvent(MyEvent event) {
            System.out.println("现在开始执行监听器中的内容,我是打Compoent注解的方式进行的");
            System.out.println("event.getSource() = " + event.getSource());
        }
    }
    Copy after login

    3: Publish the event and then perform startup class testing.

    @SpringBootApplication
    public class EventTestApplication {
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(EventTestApplication.class, args);
            //发布事件
            context.publishEvent(new MyEvent("source"));
            context.close();
        }
    }
    Copy after login
    Copy after login

    The third type

    all use annotations

    1: Same as the first type 1

    2: Create A listener.

    /**
     *第三种:采用@EventListener注解的方式,不需要在类上实现ApplicationListener接口。
     * 直接采用的是通过注解,将方法标识为一个监听器。
     * */
    @Component
    public class MyEventListener3 {
        @Async//异步注解。开启一个新线程。 去掉此注解则会变成同步监听。
        @EventListener(classes = MyEvent.class)
        public void TestListener(MyEvent myEvent){
            System.out.println("我是@EventListener注解的方式实现的监听器");
            System.out.println("myEvent.getSource() = " + myEvent.getSource());
        }
    }
    Copy after login

    3: Publish the event and then perform startup class testing.

    @SpringBootApplication
    public class EventTestApplication {
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(EventTestApplication.class, args);
            //发布事件
            context.publishEvent(new MyEvent("source"));
            context.close();
        }
    }
    Copy after login
    Copy after login

    The following is the structure diagram of the code:

    How to start a listening thread to perform tasks in springboot

    The above is the detailed content of How to start a listening thread to perform tasks in springboot. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template