ApplicationEventPublisher的publishEvent实现异步快速。 首先来一个小demo感受一下spring的自定义异步事件。
- 使用ApplicationEventPublisher的publishEvent来发布事件。如下代码,这里的事件指user
idea工具可以识别是事件,我们可以在idea编辑器中看到前面的标示。点一下即可跳转到监听事件中。
@Service
public class UserEventRegister {
@Autowired
private ApplicationEventPublisher publisher;
public void register() throws Exception {
UserDto user=new UserDto();
user.setName("电脑");
user.setSex("未知");
publisher.publishEvent(user);
}
}
- 使用@EventListener来监听事件。
condition是指条件,这里我学的为用户的姓名不为空。这里的condition使用的是SpEL表达式
@Component
public class UserEventListener {
@EventListener(condition = "#user.name!=null")
public void handleEvent(UserDto user) throws Exception{
System.out.println(user.getName());
System.out.println(user.getSex());
}
}
- 调用一下 ,看一下效果
@Controller
@Api(description = "事件接口")
@RequestMapping("/event")
public class PublishEventController {
@Autowired
private UserEventRegister register;
@GetMapping("/registerUser")
@ResponseBody
public void register() {
try {
register.register();
} catch (Exception e) {
e.printStackTrace();
}
}
}
效果如下:
demo已上传git,地址为: https://github.com/feizai1010/springboot_cache.git