需求
这里做一个简答的例子来说明事件。当成功注册一个用户后给用户发送一条注册成功的短信,该如何设计这个功能呢?当然你可以注册成功发送一条短信,然后返回注册成功,但是这样还不是最佳的。使用消息队列感觉大可不必,所以可以使用Java的事件机制来处理此类优先级不是特别重要的业务。
编写自定义事件
import org.springframework.context.ApplicationEvent;/*** @author RickSun* @Description 注册成功事件**/public class RegisterSuccessEvent extends ApplicationEvent {private static final long serialVersionUID = 1L;/*** @author RickSun* @Description 传入一个手机号**/public RegisterSuccessEvent(String telephone) {super(telephone);}}
编写事件监听
import com.beto.hdtyhealthy.core.event.RegisterSuccessEvent;import lombok.extern.slf4j.Slf4j;import org.springframework.context.ApplicationListener;import org.springframework.scheduling.annotation.Async;import org.springframework.stereotype.Component;/*** @author RickSun* @Description 监听注册成功事件**/@Slf4j@Componentpublic class RegisterSuccessEventListener implements ApplicationListener<RegisterSuccessEvent> {/** you can @Autowired something to here **/@Async //使用@Async表示异步,若没有该注解表示同步public void onApplicationEvent(RegisterSuccessEvent registerSuccessEvent) {String telephone = (String)registerSuccessEvent.getSource();log.info("------------->注册成功,即将发送短信:{}",telephone);//TODO SOMETHINGreturn;}}
编写事件发布者
@RestController@RequestMapping("/test")public class TestController {@Autowiredprivate ApplicationContext applicationContext;@PostMapping("/sendMsg")public void sendMsg(){applicationContext.publishEvent(new RegisterSuccessEvent("137XXXX1234"));}}
注意,若要@Async有效必须在启动类添加@EnableAsync,否则依然为同步事件。如下:
@SpringBootApplication@EnableAsyncpublic class FastBootApplication {public static void main(String[] args) {SpringApplication.run(FastBootApplication.class,args);}}
好了,启动起来,调用该接口后可在控制面板上看到如下输出,更多应用请移步至:
https://gitee.com/sunalee/fastboot
17:19:03.200 [INFO] RegisterSuccessEventListener [] - ------------->注册成功,即将发送短信:137XXXX1234
【更多精彩】

文章转载自笔记有云,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




