spring boot系列3-四步完成观察者事件发布接收(发送消息接收消息)使用异步方不阻塞主线程

猿份哥 5月前 ⋅ 130 阅读

1.首先Application开启异步

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


 2.定义事件体(消息)

@Setter
@Getter
@ToString
public class ContentEvent extends ApplicationEvent {
 
    private String content;
 
    /**
     * Create a new ApplicationEvent.
     * @param source the object on which the event initially occurred (never {@code null})
     */
    public ContentEvent(Object source) {
        super(source);
    }
    public ContentEvent(Object source, String content){
        super(source);
        this.content = content;
    }
}


 3.定义事件监听者(接收者)

 
@Component
@Slf4j
public class ContentListener{
 
    @Async
    @EventListener
    public void handler(ContentEvent event){
        log.info("收到消息"+event.getContent());
    }
}


 4.发布事件(发送消息)

@Controller
public class ContentController {
    @Autowired
    private ApplicationContext applicationContext;
 
    @GetMapping("/event/{content}")
    public void sendEvent(@PathVariable String content){
        applicationContext.publishEvent(new ContentEvent(this,content));
    }
}


源码下载链接: https://github.com/tiankonglanlande/springboot


全部评论: 0

    我有话说: