Spring implements asynchronous processing of events

/**
 * custom events
 * Created by szy on 2017/3/30.
 */
public class DemoEvent extends ApplicationEvent {

    private String msg;
    private List<String> list;

    public DemoEvent(Object source,String msg,List<String> list) {
        super(source);
        this.msg=msg;
        this.list = list;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }
}



/**
 * custom listener
 * Created by szy on 2017/3/30.
 */
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {

    @Async
    @Override
    public void onApplicationEvent(DemoEvent demoEvent) {
        try {
            System.out.println(Thread.currentThread().getName());
            //Simulate business time
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }
        String msg = demoEvent.getMsg();

        System.out.println("receive msg from demoevent publish : "+msg);
        System.out.println(
                "receive list from demoevent publish : "
                        +demoEvent.getList().toString());
    }
}


/**
 * Event publishing class
 *
 * Created by szy on 2017/3/30.
 */
@Component
public class DemoPublish {

    @Autowired
    private ApplicationContext applicationContext;

    public void publish(String msg, List<String> list){

        applicationContext.publishEvent(new DemoEvent(this,msg,list));

    }
}



/**
 * Created by szy on 2017/3/30.
 */
@RestController
public class DemoController {
    @Autowired
    private ApplicationContext ctx;

    @RequestMapping("/")
    public void test(){
        DemoPublish demoPublish = ctx.getBean (DemoPublish.class);
        List<String> list = new ArrayList<>();
        list.add("huahua");
        list.add("huahua1");
        list.add("huahua2");
        demoPublish.publish("hello young!",list);
        System.out.println("end");
    }

}



/**
*Startup class
*/
@SpringBootApplication
@EnableAsync
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326479330&siteId=291194637