springboot之同步與異步


1異步與同步

以一個例子解釋:李明拿100w去買房子,

同步的步驟是1李明用手機支付100w給銷售部的負責人jimao,2jimao收到錢,然后3把房子的鑰匙給李明

異步的步驟是上面的123步驟同一時間進行

2異步代碼

2.1 創建一個空的springboot項目

可以參考 [ 超鏈接 ]+ ( https://www.cnblogs.com/zhushilai/p/14006484.html ) 中的創建方式

<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.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring_task</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring_task</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
<dependencies>
<!-- web依賴的jar  -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</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<String> task4() throws InterruptedException {
long begin=System.currentTimeMillis();
Thread.sleep(3000L);
long end =System.currentTimeMillis();
System.out.println("任務4耗時:"+(end-begin));
return new AsyncResult<String>("任務4");
}

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

public Future<String> task6() throws InterruptedException {
long begin=System.currentTimeMillis();
Thread.sleep(1000L);
long end =System.currentTimeMillis();
System.out.println("任務6耗時:"+(end-begin));
return new AsyncResult<String>("任務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<String> task4=asyncTest.task4();
Future<String> task5=asyncTest.task5();
Future<String> 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

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM