springboot之同步与异步


1异步与同步

以一个例子解释:李明拿100w去买房子,

同步的步骤是1李明用手机支付100w给销售部的负责人jimao,2jimao收到钱,然后3把房子的钥匙给李明

异步的步骤是上面的123步骤同一时间进行

2异步代码

2.1 创建一个空的springboot项目

可以参考 [ 超链接 ]+ ( ) 中的创建方式

<a href="https://www.cnblogs.com/zhushilai/p/14006484.html" target="_blank">超链接a>

 

2.2 pom.xml添加依赖包

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.3.3.RELEASEversion>
<relativePath/>
parent>
<groupId>com.examplegroupId>
<artifactId>spring_taskartifactId>
<version>0.0.1-SNAPSHOTversion>
<name>spring_taskname>
<description>Demo project for Spring Bootdescription>
?
<properties>
<java.version>1.8java.version>
<maven-jar-plugin.version>3.1.1maven-jar-plugin.version>
properties>
<dependencies>

<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>

<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
?
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
?
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
?
project>
?

2.3创建异步类AsyncTest

package com.example.spring_task.async;
?
import java.util.concurrent.Future;
?
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
?
/**
* 异步任务业务类
* @author Administrator
* @Async 异步注解,可以标记在类上面,作用于类中的所有方法,也可以标记在方法上面
*/
@Component
@Async
public class AsyncTest {

public void task1() throws InterruptedException {
long begin=System.currentTimeMillis();
Thread.sleep(1000L);
long end =System.currentTimeMillis();
System.out.println("任务1耗时:"+(end-begin));
}

public void task2() throws InterruptedException {
long begin=System.currentTimeMillis();
Thread.sleep(2000L);
long end =System.currentTimeMillis();
System.out.println("任务2耗时:"+(end-begin));
}

public void task3() throws InterruptedException {
long begin=System.currentTimeMillis();
Thread.sleep(3000L);
long end =System.currentTimeMillis();
System.out.println("任务3耗时:"+(end-begin));
}
//获取异步结果
public Future task4() throws InterruptedException {
long begin=System.currentTimeMillis();
Thread.sleep(3000L);
long end =System.currentTimeMillis();
System.out.println("任务4耗时:"+(end-begin));
return new AsyncResult("任务4");
}

public Future task5() throws InterruptedException {
long begin=System.currentTimeMillis();
Thread.sleep(2000L);
long end =System.currentTimeMillis();
System.out.println("任务5耗时:"+(end-begin));
return new AsyncResult("任务5");
}

public Future task6() throws InterruptedException {
long begin=System.currentTimeMillis();
Thread.sleep(1000L);
long end =System.currentTimeMillis();
System.out.println("任务6耗时:"+(end-begin));
return new AsyncResult("任务6");
}

}
?

2.4 添加Controller

AsyncController

package com.example.spring_task.controller;
?
?
import java.util.concurrent.Future;
?
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
?
import com.example.spring_task.async.AsyncTest;
import com.example.spring_task.utils.JsonData;
?
@RestController
@RequestMapping("/api/v1")
public class AsyncController {
?
/**
* 将异步类注解进来
*/
@Autowired
private AsyncTest asyncTest;

@GetMapping("asyncTest")
public JsonData exetask() throws InterruptedException {
long begin=System.currentTimeMillis();
// asyncTest.task1();
// asyncTest.task2();
// asyncTest.task3();
Future task4=asyncTest.task4();
Future task5=asyncTest.task5();
Future task6=asyncTest.task6();
for (;;) {
if(task4.isDone()&&task5.isDone()&&task6.isDone()) {
break;
}
}

long end=System.currentTimeMillis();
long total=end-begin;
System.out.println("执行总耗时"+total);
return JsonData.buildSuccess(total);
}
}
?

2.5添加工具类JsonData

JsonData

package com.example.spring_task.utils;
?
import java.io.Serializable;
?
public class JsonData implements Serializable{
private static final long serialVersionUID = 1L;
/**
* 状态码
* 0表示成功;1表示处理中;-1表示失败
*/
private Integer code;
/**
* 数据
*/
private Object data;
/**
* 描述
*/
private String msg;
public JsonData(Integer code, Object data, String msg) {
super();
this.code = code;
this.data = data;
this.msg = msg;
}
/**
* 成功,传入数据
* @return
*/
public static JsonData buildSuccess() {
return new JsonData(0,null,null);
}

/**
* 成功,传入数据
* @return
*/
public static JsonData buildSuccess(Object data) {
return new JsonData(0,data,null);
}
/**
* 成功,传入数据和状态码
* @param data
* @param code
* @return
*/
public static JsonData buildSuccess(Object data,Integer code) {
return new JsonData(code,data,null);
}
/**
* 成功,传入状态码和信息
* @param msg
* @param code
* @return
*/
public static JsonData buildSuccess(String msg,Integer code) {
return new JsonData(code,msg,null);
}


/**
* 失败,传入描述信息
* @return
*/
public static JsonData buildError(String msg) {
return new JsonData(-1,null,msg);
}

/**
* 失败,传入信息和状态码
* @param msg
* @param code
* @return
*/
public static JsonData buildError(String msg,Integer code) {
return new JsonData(code,null,msg);
}
/**
* 失败,出入数据和状态码
* @param data
* @param code
* @return
*/
public static JsonData buildError(Object data,Integer code) {
return new JsonData(code,data,null);
}

public JsonData() {}


public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return "JsonData [code=" + code + ", data=" + data + ", msg=" + msg + "]";
}
}
?

2.6 给application添加注解

package com.example.spring_task;
?
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
*
* @author Administrator
* @SpringBootApplication 扫描所有类
* @EnableScheduling 开启定时任务
* @EnableAsync 开启异步类
*/
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class SpringTaskApplication {
?
public static void main(String[] args) {
SpringApplication.run(SpringTaskApplication.class, args);
}
?
}
?

2.7执行接口接口

接口地址:localhost:8080/api/v1/asyncTest

接口结果:

任务6耗时:1000
任务5耗时:2000
任务4耗时:3000
执行总耗时3104

3同步代码

和上面的异步代码一样,只需要将异步类中的注解@Async注释掉

接口地址:localhost:8080/api/v1/asyncTest

接口结果:

任务4耗时:3000
任务5耗时:2001
任务6耗时:1000
执行总耗时6004