SpringBoot自定义注解+异步+观察者模式实现业务日志保存( 三 )

5. 事件发布事件发布是由ApplicationContext对象进行发布的,直接注入使用即可!使用观察者模式的目的:为了业务逻辑之间的解耦,提高可扩展性 。这种模式在spring和springboot底层是经常出现的,大家可以去看看 。发布者只需要关注发布消息,监听者只需要监听自己需要的,不管谁发的,符合自己监听条件即可 。
import com.example.demo.entity.SysLog;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ApplicationContext;import org.springframework.stereotype.Component;/** * @author wangzhenjun * @date 2022/10/26 16:38 */@Componentpublic class EventPubListener {@Autowiredprivate ApplicationContext applicationContext;// 事件发布方法public void pushListener(SysLog sysLogEvent) {applicationContext.publishEvent(sysLogEvent);}}6. 监听者@Async:单独开启一个新线程去保存,提高效率!@EventListener:监听
/** * @author wangzhenjun * @date 2022/10/25 15:22 */@Slf4j@Componentpublic class MyEventListener {@Autowiredprivate TestService testService; // 开启异步@Async// 开启监听@EventListener(SysLog.class)public void saveSysLog(SysLog event) {log.info("=====即将异步保存到数据库======");testService.saveLog(event);}}五、测试1. controller/** * @author wangzhenjun * @date 2022/10/26 16:51 */@Slf4j@RestController@RequestMapping("/test")public class TestController {@Log(title = "测试呢",businessType = BusinessTypeEnum.INSERT)@GetMapping("/saveLog")public void saveLog(){log.info("我就是来测试一下是否成功!");}}2. service/** * @author wangzhenjun * @date 2022/10/26 16:55 */public interface TestService {int saveLog(SysLog sysLog);}/** * @author wangzhenjun * @date 2022/10/26 16:56 */@Servicepublic class TestServiceImpl implements TestService {@Autowiredprivate TestMapper testMapper;@Overridepublic int saveLog(SysLog sysLog) {return testMapper.insert(sysLog);}}3. mapper这里使用mybatis-plus进行保存
/** * @author wangzhenjun * @date 2022/10/26 17:07 */public interface TestMapper extends BaseMapper<SysLog> {}4. 测试

SpringBoot自定义注解+异步+观察者模式实现业务日志保存

文章插图
5. 数据库
SpringBoot自定义注解+异步+观察者模式实现业务日志保存

文章插图
六、总结铛铛铛,终于完成了!这个实战在企业级必不可少的,每个项目搭建人不同,但是结果都是一样的,保存日志到数据,这样可以进行按钮的点击进行统计,分析那个功能是否经常使用,那些东西需要优化 。只要是有数据的东西,分析一下总会有收获的!后面日志多了就行分库分表,ELK搭建 。知道的越多不知道的就越多,这一次下来,知道下面要学什么了嘛!!
可以看下一小编的微信公众号,和网站文章首发看,欢迎关注,一起交流哈!!![](https://img2022.cnblogs.com/blog/2471401/202210/2471401-20221028085553420-1506161649.jpg)
点击访问!小编自己的网站,里面也是有很多好的文章哦!
【SpringBoot自定义注解+异步+观察者模式实现业务日志保存】

经验总结扩展阅读