后台程序采用异步方式处理,以获取GitHub用户信息为例。
1 简单用户model类
package creating.asynchronous.methods.hello;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown=true)
public class User {
private String name;
private String blog;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBlog() {
return blog;
}
public void setBlog(String blog) {
this.blog = blog;
}
@Override
public String toString() {
return "User [name=" + name + ", blog=" + blog + "]";
}
}
2 异步处理的Service类
package creating.asynchronous.methods.hello;
import java.util.concurrent.Future;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class GitHubLookupService {
RestTemplate restTemplate = new RestTemplate();
public Future<User> findUser(String user) throws InterruptedException{
System.out.println("Looking up " + user);
User results = restTemplate.getForObject("https://api.github.com/users/" + user, User.class);
// Artificial delay of 1s for demonstration purposes
Thread.sleep(1000L);
return new AsyncResult<User>(results);
}
}
说明:
@Service annotation, making it a candidate for Spring’s component scanning to detect it and add it to the application context.
@Async annotation, indicating it will run on a separate thread. The method’s return type is Future instead of User, a requirement for any asynchronous service.
AsyncResult to wrap the results of the GitHub query.
3 Application
package creating.asynchronous.methods.hello;
import java.util.concurrent.Future;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class Application implements CommandLineRunner {
@Autowired
GitHubLookupService gitHubLookupService;
public void run(String... args) throws Exception {
//Start the clock
long start = System.currentTimeMillis();
//Kick of multiple, asynchronous lookups
Future<User> page1 = gitHubLookupService.findUser("PivotalSoftware");
Future<User> page2 = gitHubLookupService.findUser("CloudFoundry");
Future<User> page3 = gitHubLookupService.findUser("Spring-Projects");
//Wait until they are all done
while(!(page1.isDone() && page2.isDone() && page3.isDone())){
Thread.sleep(10);
}
System.out.println("Elapsed time: " + (System.currentTimeMillis() - start));
System.out.println(page1.get());
System.out.println(page2.get());
System.out.println(page3.get());
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}