SpringBoot方法启动新的线程异步执行的注解

时间:2024-7-24    作者:老大夫    分类: 尚庭公寓


  1. 方法上增加@Async注解
  2. SpringBoot启动类上增加@EnableAsync注解

执行该方法时就会启动新的线程处理

 @Override
    //异步操作,Spring提供的新建线程的注解,这要执行这个方法SpringBoot就会启动一个新的线程来处理,也要在SpringBoot启动类上增加注解@EnableAsync
    @Async
    public void saveHistory(Long userId, Long id) {
        //只有用户首次浏览才保存
        LambdaQueryWrapper<BrowsingHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BrowsingHistory::getUserId,userId);
        queryWrapper.eq(BrowsingHistory::getRoomId,id);
        BrowsingHistory browsingHistory = browsingHistoryMapper.selectOne(queryWrapper);
        //浏览过,直接更新浏览时间插入数据库
        if(browsingHistory!=null){
            browsingHistory.setBrowseTime(new Date());
            browsingHistoryMapper.updateById(browsingHistory);
        }else {
            //没浏览过插入新的浏览数据,房间id,用户id和浏览时间
            BrowsingHistory history = new BrowsingHistory();
            history.setRoomId(id);
            history.setUserId(LoginUserHolder.getLoginUser().getUserId());
            history.setBrowseTime(new Date());
            browsingHistoryMapper.insert(history);

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


扫描二维码,在手机上阅读

推荐阅读: