The use of Spring-boot @Async, the configuration method of custom executor _spring-boot

Source: Internet
Author: User

Simple steps to implement asynchronous new thread invocation.


1. Add @enableasync annotation to main class:

@SpringBootApplication
@EnableScheduling
@EnableAsync public
class Myspringbootapplication {
	private static Logger Logger = Loggerfactory.getlogger (myspringbootapplication.class);
	
	public static void Main (string[] args) {
		springapplication.run (myspringbootapplication.class, args);
		Logger.info ("My Spring Boot application Started");
	}

	

2. Create a Asynctask class and add two tasks with @async annotations in it:

/**
 * Asynchronous Tasks
 * @author Xu
 * * * * * */
@Component Public
class Asynctask {
	protected Final Logger Logger = Loggerfactory.getlogger (This.getclass ());
	
	@Async public
	future<string> DoTask1 () throws interruptedexception{
		Logger.info ("Task1 started.");
		Long start = System.currenttimemillis ();
        Thread.Sleep (5000);
        Long end = System.currenttimemillis ();
        
        Logger.info ("Task1 Finished, time elapsed: {} ms.", End-start);
        
        return new Asyncresult<> ("Task1 accomplished!");
	}
	
	@Async public
	future<string> DoTask2 () throws interruptedexception{
		Logger.info ("Task2 started.");
		Long start = System.currenttimemillis ();
        Thread.Sleep (3000);
        Long end = System.currenttimemillis ();
        
        Logger.info ("Task2 Finished, time elapsed: {} ms.", End-start);
        
        return new Asyncresult<> ("Task2 accomplished!");
	}
3, everything is ready to start testing:

public class Tasktests extends basicutclass{
	@Autowired
	private asynctask asynctask;
	
	
	@Test public
	void Asynctasktest () throws Interruptedexception, executionexception {
		future<string> Task1 = Asynctask.dotask1 ();
		future<string> Task2 = Asynctask.dotask2 ();
		
		while (true) {
			if (Task1.isdone () && Task2.isdone ()) {
				logger.info (' Task1 result: {} ', Task1.get ());
				Logger.info ("Task2 result: {}", Task2.get ());
				break;
			Thread.Sleep (1000);
		}
		
		Logger.info ("All Tasks finished.");
	}

Test results:

2016-12-13 11:12:24,850:info Main (asyncexecutionaspectsupport.java:245)-No taskexecutor Bean found for async processin G
2016-12-13 11:12:24,864:info SimpleAsyncTaskExecutor-1 (asynctask.java:22)-Task1 started.
2016-12-13 11:12:24,865:info SimpleAsyncTaskExecutor-2 (asynctask.java:34)-Task2 started.
2016-12-13 11:12:27,869:info SimpleAsyncTaskExecutor-2 (asynctask.java:39)-Task2 finished, time elapsed:3001 Ms.
2016-12-13 11:12:29,866:info SimpleAsyncTaskExecutor-1 (asynctask.java:27)-Task1 finished, time elapsed:5001 Ms.
2016-12-13 11:12:30,853:info Main (tasktests.java:23)-Task1 result:task1
accomplished! 2016-12-13 11:12:30,853:info Main (tasktests.java:24)-Task2 result:task2
accomplished! 2016-12-13 11:12:30,854:info Main (tasktests.java:30)-All tasks finished.

As you can see, there is no custom executor, so use the default taskexecutor.


The easiest way to use it is before. If you want to use a custom executor, you can follow these steps:

1, a new executor configuration class, by the way @enableasync annotation moved here:

@Configuration @EnableAsync public class Executorconfig {/** Set the Threadpoolexecutor ' s core pool size. * * Private I
	NT Corepoolsize = 10; /** Set The Threadpoolexecutor ' s maximum pool size.
	* Private int maxpoolsize = 200; /** Set The capacity for the Threadpoolexecutor ' s blockingqueue.

	* Private int queuecapacity = 10;
		@Bean public Executor Mysimpleasync () {threadpooltaskexecutor Executor = new Threadpooltaskexecutor ();
		Executor.setcorepoolsize (corepoolsize);
		Executor.setmaxpoolsize (maxpoolsize);
		Executor.setqueuecapacity (queuecapacity);
		Executor.setthreadnameprefix ("mysimpleexecutor-");
		Executor.initialize ();
	return executor;
		@Bean public Executor Myasync () {threadpooltaskexecutor Executor = new Threadpooltaskexecutor ();
		Executor.setcorepoolsize (corepoolsize);
		Executor.setmaxpoolsize (maxpoolsize);
		Executor.setqueuecapacity (queuecapacity);

		Executor.setthreadnameprefix ("myexecutor-");
		Rejection-policy: How to handle new tasks when pool has reached max sizeCaller_runs: Does not perform a task in a new thread, but rather the thread where the caller is executing the Executor.setrejectedexecutionhandler (new
		Threadpoolexecutor.callerrunspolicy ());
		Executor.initialize ();
	return executor; }
}

This defines two different executor, and the second sets the processing method of the pool when Max size is reached, and specifies the prefix for the thread name.

2, the use of custom executor:

/** * Asynchronous Tasks * @author Xu */@Component public class Asynctask {protected final Logger Logger = L
	
	Oggerfactory.getlogger (This.getclass ()); @Async ("Mysimpleasync") public future<string> DoTask1 () throws interruptedexception{Logger.info ("Task1 started
		.");
        Long start = System.currenttimemillis ();
        Thread.Sleep (5000);
        
        Long end = System.currenttimemillis ();
        
        Logger.info ("Task1 Finished, time elapsed: {} ms.", End-start);
	return new Asyncresult<> ("Task1 accomplished!"); @Async ("Myasync") public future<string> DoTask2 () throws interruptedexception{Logger.info ("Task2 started.").
		);
        Long start = System.currenttimemillis ();
        Thread.Sleep (3000);
        
        Long end = System.currenttimemillis ();
        
        Logger.info ("Task2 Finished, time elapsed: {} ms.", End-start);
	return new Asyncresult<> ("Task2 accomplished!"); }
}
is to put the above custom executor class name, into the @async annotation.


3. Test (test case unchanged) Result:

2016-12-13 10:57:11,998:info MySimpleExecutor-1 (asynctask.java:22)-Task1 started.
2016-12-13 10:57:12,001:info MyExecutor-1 (asynctask.java:34)-Task2 started.
2016-12-13 10:57:15,007:info MyExecutor-1 (asynctask.java:39)-Task2 finished, time elapsed:3000 Ms.
2016-12-13 10: 57:16,999:info MySimpleExecutor-1 (asynctask.java:27)-Task1 finished, time elapsed:5001 Ms.
2016-12-13 10:57:17,994:info Main (tasktests.java:23)-Task1 result:task1 accomplished!
2016-12-13 10:57:17,994:info Main (tasktests.java:24)-Task2 result:task2
accomplished! 2016-12-13 10:57:17,994:info Main (tasktests.java:30)-All tasks finished.
2016-12-13 10:57:18,064 Thread-3 WARN Unable to register log4j shutdown hook because JVM are shutting down. Using Simplelogger

As you can see, the prefix for the thread name changes, and two tasks use a different thread pool.

Source code: Https://github.com/xujijun/my-spring-boot






Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.