场景:main方法本地引入其他对象是不收托管的。需要自己手动注入。
以下仅是个参考例子。(用于本地简易异步线程池使用)
· 以下是main方法测试类
package com.springboot.redisdemo.controller;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* @Author lhp
* @Date 2020/8/31 14:49
* @Version 1.0
* @Description
*/
@Slf4j
@RestController
@RequestMapping("aaa")
public class RedisController {
public static void main(String[] args) throws InterruptedException {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("application.xml");
RedisController redisController = (RedisController)classPathXmlApplicationContext.getBean("RedisController");
System.out.println("1线程开始了");
Future<Integer> integerFuture1 = redisController.test1();
System.out.println("2线程开始了");
Future<Integer> integerFuture2 = redisController.test2();
System.out.println("3线程开始了");
Future<Integer> integerFuture3 = redisController.test3();
}
/**
*
* 异步线程test1
*/
@Async("WhifExecutor")
Future<Integer> test1() throws InterruptedException {
System.out.println("1线程进来了");
Thread.sleep(3000);
System.out.println("test1异步线程结束了");
return new AsyncResult<>(123);
}
/**
*
* 异步线程test2
*/
@Async("WhifExecutor")
Future<Integer> test2() throws InterruptedException {
System.out.println("2线程进来了");
Thread.sleep(4000);
System.out.println("test2异步线程结束了");
return new AsyncResult<>(123);
}
/**
*
* 异步线程test3
*/
@Async("WhifExecutor")
Future<Integer> test3() throws InterruptedException {
System.out.println("3线程进来了");
Thread.sleep(5000);
System.out.println("test3异步线程结束了");
return new AsyncResult<>(123);
}
}
- 以下是 xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<task:executor id="WhifExecutor" pool-size="10"/>
<task:annotation-driven executor="WhifExecutor" />
<bean id="RedisController" class="com.springboot.redisdemo.controller.RedisController"></bean>
</beans>
注意:不管是Bean还是线程池的注入都需要id与引入的类对应上。
- 实现结果
这样,@async注解就生效咯