异步demo
序言在日常开发中,有很多时候都会使用异步的方式去请求方法,以提高代码的执行效率。比如用户购买某件商品,然后需要插入购买记录,物品-1,微信公众号消息推送之类,流程会很多,也会需要很多时间,而 SpringBoot 为异步提供了更加简单的使用方式,通过两个注解即可实现异步调用方法。
1、使用方式SpringBoot 为我们提供了很多使用便利,我们只需要一个@Enablexxx 注解 + 功能注解,便能轻松简单的实现功能,比如异步调用和定时任务。
1.1 简单使用异步调用(无返回调用)假定使用场景:用户购买完一件商品,需要短信通知 + 微信消息推送(不考虑失败场景),不需要返回值。
注意:下面代码是为了展现一个之前一直困惑我的问题,所以代码有些问题,解决办法看下面:
Service 层,模拟功能实现:
@Servicepublic class AsyncMsgService { private static final Logger logger = LoggerFactory.getLogger(AsyncMsgService.class); @Async ...
@Async和@EnableAsync注解
1) 含义:1,在方法上使用该@Async 注解,申明该方法是一个异步任务;
2,在类上面使用该@Async 注解,申明该类中的所有方法都是异步任务;
3,使用此注解的方法的类对象,必须是 spring 管理下的 bean 对象;
4,要想使用异步任务,需要在主类上开启异步配置,即,配置上@EnableAsync 注解;
2) 使用:在 Spring 中启用@Async:
1,@Async 注解在使用时,如果不指定线程池的名称,则使用 Spring 默认的线程池,Spring 默认的线程池为SimpleAsyncTaskExecutor。
2,方法上一旦标记了这个@Async 注解,当其它线程调用这个方法时,就会开启一个新的子线程去异步处理该业务逻辑。
3) 代码示例—默认线程池:3.1,启动类中增加@EnableAsync以 Spring boot 为例,启动类中增加@EnableAsync:
@EnableAsync@SpringBootApplicationpublic class ManageApplication { //...}
3.2,方法上 ...
hello world
值此博客建站成功之际,难以抑制内心的激动心情只好写一行 hello world 了 😄😄😄
public static void main(String[] args){ System.out.println("hello world");}
写完了 hello world,然后就是测试主题 butterfly 的各种功能
测试 toc 功能一级标题111
二级标题222
三级标题333
还要整合的模块
[x] 评论系统
[x] 搜索系统
[ ] 网站验证
[ ] 广告
公式测试(mathjax)
e^{i\theta}=\cos\theta+i\sin\theta