Created
March 25, 2020 18:27
-
-
Save mstephenson6/760a41b5d9c9a9601c86aa0ad369862d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.demo; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.scheduling.annotation.Async; | |
import org.springframework.scheduling.annotation.AsyncResult; | |
import org.springframework.stereotype.Component; | |
import java.util.concurrent.Future; | |
import java.util.concurrent.ThreadLocalRandom; | |
@Component | |
public class AsyncWorkers { | |
private final Logger logger = LoggerFactory.getLogger(AsyncWorkers.class); | |
@Async | |
public Future<String> longRunningTask(int n) { | |
logger.info("longRunningTask() has started"); | |
try { | |
Thread.sleep(ThreadLocalRandom.current().nextInt(3000, 5000)); | |
} | |
catch (InterruptedException ie) { | |
// do nothing! | |
} | |
String result = ""; | |
for (int i=0; i<n; ++i) { | |
result += i + " "; | |
} | |
logger.info("longRunningTask() is returning"); | |
return new AsyncResult<>(result); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.demo; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.boot.CommandLineRunner; | |
import org.springframework.stereotype.Component; | |
@Component | |
public class CmdLine implements CommandLineRunner { | |
private final Logger logger = LoggerFactory.getLogger(CmdLine.class); | |
@Autowired | |
private AsyncWorkers asyncWorkers; | |
@Override | |
public void run(String... args) throws Exception { | |
logger.info("run() has started"); | |
asyncWorkers.longRunningTask(5); | |
logger.info("run() has finished"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.demo; | |
import org.springframework.boot.SpringApplication; | |
import org.springframework.boot.autoconfigure.SpringBootApplication; | |
import org.springframework.scheduling.annotation.EnableAsync; | |
@SpringBootApplication | |
@EnableAsync | |
public class DemoApplication { | |
public static void main(String[] args) { | |
SpringApplication.run(DemoApplication.class, args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment