当前位置:网站首页>SSM use @async and create threadpooltaskexecutor thread pool
SSM use @async and create threadpooltaskexecutor thread pool
2022-07-28 21:13:00 【Hu Anmin】
Please see the specific configuration suggestions of thread pool : http://t.csdn.cn/nWaGH
Thread pool used directly in the project
stay applicationContext.xml Add in
<bean id="userService" class="com.ssm.service.impl.UserServiceImpl">
<property name="executor">
<bean class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<property name="threadNamePrefix" value="user-"/>
<property name="corePoolSize" value="20"/>
<property name="maxPoolSize" value="20"/>
<property name="keepAliveSeconds" value="300"/>
<property name="queueCapacity" value="100"/>
</bean>
</property>
</bean>
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
private AsyncTaskExecutor executor;
public void setExecutor(AsyncTaskExecutor executor) {
this.executor = executor;
}
public void getUserList() {
// Multithreading
executor.execute(()->{
System.out.println("========");
});
}
}
Configure asynchrony @Async
stay applicationContext.xml Create files in the same directory threadPool.xml file
<?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: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/task http://www.springframework.org/schema/task/spring-task.xsd">
<!-- Open asynchronous , And introduce thread pool This tag is used to enable detection of any Spring Managed bean Upper @Async and @Scheduled annotation -->
<task:annotation-driven executor="threadPool" />
<!-- Define thread pool -->
<bean id="threadPool" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- Number of core threads , This is used by the whole system, so it is calculated according to the visits of the system ( Peak second visits *1.5) -->
<property name="corePoolSize" value="1000" />
<!-- Maximum number of threads , The default is Integer.MAX_VALUE -->
<property name="maxPoolSize" value="1000" />
<!-- The maximum queue length is recommended (corePoolSize*2) -->
<property name="queueCapacity" value="2000" />
<!-- The thread pool maintains the free time allowed for threads , The default is 60s -->
<property name="keepAliveSeconds" value="300" />
<!-- Thread pool to reject task ( No threads available ) Handling strategy of , Currently only supported AbortPolicy、CallerRunsPolicy; Default to the latter -->
<property name="rejectedExecutionHandler">
<!-- CallerRunsPolicy: As long as the thread pool is not closed , The policy is directly in the caller thread , Run the current discarded task .-->
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
</property>
</bean>
</beans>
Then later in applicationContext.xml Introduction in threadPool.xml:
<import resource="threadPool.xml" />
test
The defined asynchronous method cannot be in the same class as the called asynchronous method , Otherwise it will not work
Here we simulate sending SMS after canceling the order , There are two ways to send text messages
@Service
public class TranTest2Service {
// Send a reminder message 1
@Async("threadPool")
public void sendMessage1() throws InterruptedException {
System.out.println(" How to send SMS ---- 1 Execution start ");
Thread.sleep(5000); // Simulation takes time
System.out.println(" How to send SMS ---- 1 end of execution ");
}
// Send a reminder message 2
@Async("threadPool")
public void sendMessage2() throws InterruptedException {
System.out.println(" How to send SMS ---- 2 Execution start ");
Thread.sleep(2000); // Simulation takes time
System.out.println(" How to send SMS ---- 2 end of execution ");
}
}
Call the method of sending text messages
@Autowired
private TranTest2Service tranTest2Service;
// Order processing task
@GetMapping(path = "/orderTask")
public void orderTask() throws InterruptedException {
tranTest2Service.sendMessage1(); // How to send text messages 1
tranTest2Service.sendMessage2(); // How to send text messages 2
}
Use @Async effect
Don't use @Async effect
be based on @Async Call to return value
@Async("threadPool")
public Future<String> asyncMethodWithReturnType() {
System.out.println("Execute method asynchronously - "
+ Thread.currentThread().getName());
try {
Thread.sleep(5000);
return new AsyncResult<String>("hello world !!!!");
} catch (InterruptedException e) {
//
}
return null;
}
The above example shows , The data type returned is Future type , It's an interface . The specific result type is AsyncResult, This is what needs attention .
An example of an asynchronous method that returns a result :
public void testAsyncAnnotationForMethodsWithReturnType()
throws InterruptedException, ExecutionException {
System.out.println("Invoking an asynchronous method. "
+ Thread.currentThread().getName());
Future<String> future = asyncAnnotationExample.asyncMethodWithReturnType();
// After blocking all threads , Get the content returned by the thread
future.get()
}
be based on @Async Exception handling mechanism in call
In asynchronous methods , If there is an anomaly , For the caller caller for , Is imperceptible . If you really need exception handling , Then proceed as follows :
<task:annotation-driven executor="exceptionHandlingTaskExecutor" />
<bean id="exceptionHandlingTaskExecutor" class=" com.ssm.service.impl.ExceptionHandlingAsyncTaskExecutor">
<constructor-arg ref="threadPool" />
</bean>
public class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor {
private AsyncTaskExecutor executor;
public ExceptionHandlingAsyncTaskExecutor(AsyncTaskExecutor executor) {
this.executor = executor;
}
// Wrap... With separate threads ,@Async This is the essence of it
@Override
public void execute(Runnable task) {
executor.execute(createWrappedRunnable(task));
}
@Override
public void execute(Runnable task, long startTimeout) {
// Wrap... With separate threads ,@Async This is the essence of it
executor.execute(createWrappedRunnable(task), startTimeout);
}
@Override
public Future submit(Runnable task) {
// Wrap... With separate threads ,@Async This is the essence of it .
return executor.submit(createWrappedRunnable(task));
}
@Override
public Future submit(final Callable task) {
// Wrap... With separate threads ,@Async This is the essence of it .
return executor.submit(createCallable(task));
}
private Callable createCallable(final Callable task) {
return new Callable() {
@Override
public Object call() throws Exception {
try {
return task.call();
} catch (Exception ex) {
handle(ex);
throw ex;
}
}
};
}
private Runnable createWrappedRunnable(final Runnable task) {
return new Runnable() {
@Override
public void run() {
try {
task.run();
} catch (Exception ex) {
handle(ex);
}
}
};
}
private void handle(Exception ex) {
// Specific exception logic processing place
System.err.println("Error during @Async execution: " + ex);
}
}
边栏推荐
- 详细讲解C语言12(C语言系列)
- Integrating database Ecology: using eventbridge to build CDC applications
- MFC WPF WinForm (Industrial MFC or QT)
- 【题目】两数相加
- What is low code? Which platforms are suitable for business personnel? Is it reliable to develop the system?
- 【周周有奖】云原生编程挑战赛“边缘容器”赛道邀你来战!
- ctfshow 网络迷踪做题记录(1)
- MoCo V2:MoCo系列再升级
- SharkTeam完成Flow生态NFT市场MatrixMarket的安全审计
- ntp服务器 时间(查看服务器时间)
猜你喜欢
How does lazada store make up orders efficiently? (detailed technical explanation of evaluation self-supporting number)
Tested interviewed Zuckerberg: reveal more details of four VR prototypes
npm如何切换淘宝源镜像
What is "security"? Volvo tells you with its unique understanding and action
Interpretation of netappp SP sensors output content
Confession of a graduate student: why am I addicted to opengauss community?
Sharkteam completes the safety audit of flow ecological NFT market matrixmarket
Space shooting Lesson 13: explosion effect
ctfshow 网络迷踪做题记录(2)
Applet container technology improves mobile R & D efficiency by 500%
随机推荐
Explain the imported 3D model in unity
C # basic 5-asynchronous
广和通&高通物联网技术开放日成功举办
【云原生】什么是 CI/CD ? | 摆平交付障碍的 CI/CD
Explain in detail the rays and radiographic testing in unity
取色器实战(Qt含源码)
详细讲解C语言12(C语言系列)
(转)冒泡排序及优化详解
Space shooting Lesson 11: sound and music
Observer mode, object pool
How to modify the ID of NetApp expansion enclosure disk shelf
Interesting pictures and words
Is it necessary to disconnect all connections before deleting the PostgreSQL database?
Tested interviewed Zuckerberg: reveal more details of four VR prototypes
The EMC vnx5200 fault light is on, but there is no hardware fault prompt
程序员最大的浪漫~
Basic operations of unity3d scene production
Unity foundation 1 - event execution sequence, custom events
什么是“安全感”?沃尔沃用它自己独特的理解以及行动来告诉你
Unit editor details