springboot使用多线程

首先在应用启动类添加@EnableAsync开启

@SpringBootApplication
@EnableAsync
public class MicoServiceApp {
    public static void main(String[] args) {
        SpringApplication.run(MicoServiceApp.class,args);
    }
}

在服务类的方法添加@Async

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuEntity> implements IMenuService {
    private Logger logger= LoggerFactory.getLogger(MenuServiceImpl.class);
    @Async
    public ResponseUtils getMenu(HttpServletRequest request,MenuListMapperParam menuListMapperParam){
        List<MenuEntity>list=this.baseMapper.selectEntityList(menuListMapperParam);
        try {
            Thread.sleep(5 * 1000); //设置暂停的时间 5 秒
            logger.error("走了");
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return ResponseUtils.success(list);
    }
}

其他类调用getMenu方法时这个getMenu方法是开启了异步的,加一个sleep可尝试知道
异步方法可这样添加

@Component
public class AsyncTest {
    private Logger logger= LoggerFactory.getLogger(AsyncTest.class);
    @Async
    public void timeOutTest(){
        try {
            Thread.sleep(5 * 1000); //设置暂停的时间 5 秒
            logger.error("走了");
        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }
}

猜你喜欢

转载自blog.csdn.net/chaogaoxiaojifantong/article/details/112735044
今日推荐