Spring Boot文档阅读笔记-Creating Asynchronous Methods解析

创建一个GitHub用户信息查找服务,这个服务是通过GitHub的API获取数据的。

接口是http的,如下:

这里创建一个model去接收对象:

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {

    private String name;
    private String blog;
}

@JsonIngnore告诉spring忽略其他json属性。

下面是创建GitHub检索服务,代码如下:

@Service
public class GitHubLookupService {

    private static final Logger logger = LoggerFactory.getLogger(GitHubLookupService.class);
    private final RestTemplate restTemplate;

    public GitHubLookupService(RestTemplateBuilder restTemplateBuilder){

        this.restTemplate = restTemplateBuilder.build();
    }

    public CompletableFuture<User> findUser(String user) throws InterruptedException {

        logger.info("Looking up " + user);
        String url = String.format("https://api.github.com/users/%s", user);
        User results = restTemplate.getForObject(url, User.class);
        Thread.sleep(1000L);
        return CompletableFuture.completedFuture(results);
    }
}

GItHubLookupService使用RestTemplate调用api.github.com/users,获取User对象。

AppRunner.java

@Component
public class AppRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(AppRunner.class);
    private final GitHubLookupService gitHubLookupService;

    public AppRunner(GitHubLookupService gitHubLookupService){

        this.gitHubLookupService = gitHubLookupService;
    }

    @Override
    public void run(String... args) throws Exception {

        long start = System.currentTimeMillis();

        CompletableFuture<User> pivotalSoftware = gitHubLookupService.findUser("PivotalSoftware");
        CompletableFuture<User> cloudFoundry = gitHubLookupService.findUser("CloudFoundry");
        CompletableFuture<User> user = gitHubLookupService.findUser("Spring-Projects");

        CompletableFuture.allOf(pivotalSoftware, cloudFoundry, user).join();

        logger.info("Elapsed time: " + (System.currentTimeMillis() -  start));
        logger.info("-->" + pivotalSoftware.get());
        logger.info("-->" + cloudFoundry.get());
        logger.info("-->" + user.get());
        logger.info("---------- over ----------");
    }
}

DemoApplication.java

@SpringBootApplication
@EnableAsync
public class DemoApplication {

    @Bean
    public Executor taskExecutor(){

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("GithubLookup-");
        executor.initialize();
        return executor;
    }

    public static void main(String[] args) {

        SpringApplication.run(DemoApplication.class, args);
    }

}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页