Springboot使用异步任务失败的问题
控制层代码
@RestController
@RequestMapping("novels")
public class NovelController {
@Autowired
private NovelService novelService;
@PostMapping("all/{novelNameLike}")
public DataProtocol getAllNovelUrl(@PathVariable String novelNameLike) throws ExecutionException, InterruptedException {
novelNameLike = novelNameLike.trim();
Future<Boolean> booleanFuture = novelService.insAllNovelAndChapter(novelNameLike);
Boolean flag = booleanFuture.get();
return flag ? new DataProtocol(CODE_SUCCESS, INSERT_SUCCESS, null) : new DataProtocol(CODE_ERROR, INSERT_FAILURE, null);
}
}
业务层代码
@Service
public class NovelServiceImpl implements NovelService {
@Autowired
private HttpUtils httpUtils;
@Autowired
private ChapterMapper chapterMapper;
@Autowired
private NovelMapper novelMapper;
@Override
@Async
@Transactional(propagation = Propagation.REQUIRED)
public Future<Boolean> insAllNovelAndChapter(String novelNameLike) throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
List<Novel> novels = parseAllNovel(novelNameLike); //从工具类中获取全部的小说
novelMapper.insAllNovel(novels); //添加到数据可
Future<List<List<Chapter>>> listFuture = httpUtils.getChapterList(novels); //从工具类中得到全部小说的全部章节网址
List<List<Chapter>> chapterList = listFuture.get();
for (List<Chapter> chapters : chapterList) {
chapterMapper.insAllChapter(chapters); //添加到数据库
}
long end = System.currentTimeMillis();
System.err.println("业务层执行的时间:" + (end - start) + "ms");
return new AsyncResult<>(true);
}
}
工具类代码
@Component
public class HttpUtils {
//用于爬取所有的小说的全部章节网址
@Async
public Future<List<List<Chapter>>> getChapterList(List<Novel> novels) {
List<List<Chapter>> listArrayList = new ArrayList<>();
long start = System.currentTimeMillis();
for (Novel novel : novels) {
String chapterUrl = novel.getChapterUrl();
List<Chapter> chapters = parseCharacterUrl(chapterUrl); //使用Jsoup爬取章节的类容
listArrayList.add(chapters);
}
long end = System.currentTimeMillis();
System.err.println("工具类执行的时间:" + (end - start) + "ms");
return new AsyncResult<>(listArrayList);
}
}
在控制台中输出的时间
工具类执行的时间:6748ms
业务层执行的时间:8898ms
页面响应时间:9140ms
没有使用异步任务前端的访问时间大概在:1200ms
好像异步任务失败了,这种应该怎么解决?
额,单体应用可以改成任务表驱动,分布式或者微服务改成MQ驱动,这样或许会好很多。