# Spring Boot 实战系列 - 方法异步处理

2020-01-13  本文已影响0人  柳经年

一般在一个方法中需要处理多个任务,其中某些任务无关紧要(如发送短信、记录操作日志等),可以使用异步处理那些无关紧要的任务,从而提高整个请求的相应时间。下面演示使用 Spring Boot 快速开发方法异步处理

pom.xml 依赖配置如下

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>

Controller 层代码

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/users/{id}")
    public UserDTO get(@PathVariable("id") Long id) {
        return userService.getById(id);
    }
}

Service 层代码

// 接口定义
public interface UserService {

    UserDTO getById(Long id);
}
// 接口实现
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private LogService logService;

    @Override
    public UserDTO getById(Long id) {

        log.info("查询用户");
        UserDTO userDTO = new UserDTO();
        userDTO.setId(id);

        log.info("记录操作日志");
        logService.save();

        return userDTO;
    }
}
// 接口定义
public interface LogService {

    void save();
}
// 接口实现
@Slf4j
@Service
public class LogServiceImpl implements LogService {

    @Async("logServiceExecutor") // @Async 表示该方法异步执行,"logServiceExecutor"用来指定线程池实例
    @Override
    public void save() {

        log.info("{},{},记录日志, start", Integer.toHexString(Thread.currentThread().hashCode()), Thread.currentThread().getName());
        try {
            // 休眠3秒,异步效果更明显
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("{},{},记录日志, end.", Integer.toHexString(Thread.currentThread().hashCode()), Thread.currentThread().getName());
    }
}

配置层

@Slf4j
@EnableAsync
@Configuration
public class ExecutorConfig {

    @Bean("logServiceExecutor")
    public Executor logServiceExecutor() {

        log.info("启动 Log Service Executor");

        ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 10,
                5L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(512),
                new CustomizableThreadFactory("save-log-thread-"),
                new ThreadPoolExecutor.DiscardPolicy());

        return executor;
    }
}

总结


本文完。

上一篇 下一篇

猜你喜欢

热点阅读