美文网首页
SpringBoot 异步 controller 示例

SpringBoot 异步 controller 示例

作者: SlowGO | 来源:发表于2019-01-15 15:27 被阅读14次

    下面的示例是在 springboot 的 controller 中整合异步service调用的示例。

    我们需要完成:

    1. 做一个提供测试测试数据的 controller。
    2. 创建一个异步的 service,远程调用上面的测试数据 controller。
    3. 创建一个 controller,调用多个异步 service,并等待异步调用全部完成,输出结果。

    示例

    1. 测试数据 controller

    package com.example.demoasync;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class EmployeeDataController {
        private static Logger log = LoggerFactory.getLogger(EmployeeDataController.class);
    
        @RequestMapping(value = "/addresses", method = RequestMethod.GET)
        public List<String> getAddresses() {
            log.info("get addresses Start");
    
            ArrayList<String> employeeAddresses = new ArrayList<String>();
            employeeAddresses.add("addr1");
            employeeAddresses.add("addr2");
            employeeAddresses.add("addr3");
    
            return employeeAddresses;
        }
    
        @RequestMapping(value = "/phones", method = RequestMethod.GET)
        public List<String> getPhoneNumbers() {
            log.info("get phones Start");
    
            ArrayList<String> phoneNumberList = new ArrayList<String>();
    
            phoneNumberList.add("100000");
            phoneNumberList.add("200000");
    
            return phoneNumberList;
        }
    
        @RequestMapping(value = "/names", method = RequestMethod.GET)
        public List<String> getEmployeeName() {
            log.info("get names Start");
    
            List<String> employeeList = new ArrayList<String>();
    
            employeeList.add("Santa");
            employeeList.add("Banta");
    
            return employeeList;
        }
    }
    

    2. 异步 service

    package com.example.demoasync;
    
    import java.util.List;
    import java.util.concurrent.CompletableFuture;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Service;
    import org.springframework.web.client.RestTemplate;
    
    @Service
    public class AsyncService {
    
        private static Logger log = LoggerFactory.getLogger(AsyncService.class);
    
        @Autowired
        private RestTemplate restTemplate;
    
        @Bean
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }
    
        @Async("asyncExecutor")
        public CompletableFuture<List<String>> getEmployeeName() throws InterruptedException {
            log.info("getEmployeeName starts");
    
            List<String> employeeNameData = restTemplate.getForObject("http://localhost:8080/names", List.class);
    
            log.info("employeeNameData, {}", employeeNameData);
            Thread.sleep(1000L); // Intentional delay
            log.info("employeeNameData completed");
            return CompletableFuture.completedFuture(employeeNameData);
        }
    
        @Async("asyncExecutor")
        public CompletableFuture<List<String>> getEmployeeAddress() throws InterruptedException {
            log.info("getEmployeeAddress starts");
    
            List<String> employeeAddressData = restTemplate.getForObject("http://localhost:8080/addresses", List.class);
    
            log.info("employeeAddressData, {}", employeeAddressData);
            Thread.sleep(1000L); // Intentional delay
            log.info("employeeAddressData completed");
            return CompletableFuture.completedFuture(employeeAddressData);
        }
    
        @Async("asyncExecutor")
        public CompletableFuture<List<String>> getEmployeePhone() throws InterruptedException {
            log.info("getEmployeePhone starts");
    
            List<String> employeePhoneData = restTemplate.getForObject("http://localhost:8080/phones", List.class);
    
            log.info("employeePhoneData, {}", employeePhoneData);
            Thread.sleep(1000L); // Intentional delay
            log.info("employeePhoneData completed");
            return CompletableFuture.completedFuture(employeePhoneData);
        }
    }
    

    3. controller

    package com.example.demoasync;
    
    import java.util.List;
    import java.util.concurrent.CompletableFuture;
    import java.util.concurrent.ExecutionException;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class AsyncController {
     
        private static Logger log = LoggerFactory.getLogger(AsyncController.class);
     
        @Autowired
        private AsyncService service;
     
        @RequestMapping(value = "/testAsynch", method = RequestMethod.GET)
        public void testAsynch() throws InterruptedException, ExecutionException
        {
            log.info("testAsynch Start");
     
            CompletableFuture<List<String>> employeeAddress = service.getEmployeeAddress();
            CompletableFuture<List<String>> employeeName = service.getEmployeeName();
            CompletableFuture<List<String>> employeePhone = service.getEmployeePhone();
     
            // 等待每个异步调用都完成
            CompletableFuture.allOf(employeeAddress, employeeName, employeePhone).join();
             
            log.info("EmployeeAddress--> " + employeeAddress.get());
            log.info("EmployeeName--> " + employeeName.get());
            log.info("EmployeePhone--> " + employeePhone.get());
        }
    }
    

    相关文章

      网友评论

          本文标题:SpringBoot 异步 controller 示例

          本文链接:https://www.haomeiwen.com/subject/iajydqtx.html