Springboot中使用异步调用的方法

1. @Aysnc

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {

    @Async
    public void asyncMethod() {
        System.out.println("Execute method asynchronously - " 
          + Thread.currentThread().getName());
        // 模拟长时间任务
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Async operation finished.");
    }
}

2.使用CompletableFuture

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Service
public class CompletableFutureService {

    @Async
    public CompletableFuture<String> asyncMethodWithReturnType() {
        System.out.println("Execute method asynchronously - " 
          + Thread.currentThread().getName());
        try {
            Thread.sleep(5000);
            return CompletableFuture.completedFuture("Hello from Async World");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return CompletableFuture.completedFuture("Error");
    }
}
@RestController
@RequestMapping("/api")
public class AsyncController {

    @Autowired
    private CompletableFutureService completableFutureService;

    @GetMapping("/async")
    public String callAsyncMethod() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = completableFutureService.asyncMethodWithReturnType();
        return future.get();
    }
}

3.使用消息队列

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//发送消息
@Service
public class RabbitMQSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendMessage(String message) {
        rabbitTemplate.convertAndSend("asyncQueue", message);
    }
}

//接收消息
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Service
public class RabbitMQReceiver {

    @RabbitListener(queues = "asyncQueue")
    public void receiveMessage(String message) {
        System.out.println("Received Message: " + message);
        // 处理消息
    }
}

4.ScheduledExecutorService

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
public class ScheduledExecutorServiceExample {

    private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);

    public void executeTask() {
        executorService.schedule(() -> {
            System.out.println("Executing Task - " + Thread.currentThread().getName());
        }, 5, TimeUnit.SECONDS);
    }
}

5.WebFlux

import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

@Service
public class WebFluxService {

    public Mono<String> asyncMethod() {
        return Mono.fromSupplier(() -> {
            try {
                Thread.sleep(5000);
                return "Hello from WebFlux";
            } catch (InterruptedException e) {
                e.printStackTrace();
                return "Error";
            }
        });
    }
}
@RestController
@RequestMapping("/api")
public class WebFluxController {

    @Autowired
    private WebFluxService webFluxService;

    @GetMapping("/webflux")
    public Mono<String> callAsyncMethod() {
        return webFluxService.asyncMethod();
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值