java在并行流中使用Spring存储库(多线程)
在SpringBoot应用程序中,我有多个接口实现,每个接口都使用JPA存储库访问数据库
@Autowired
List<? extends CrawlerService> crawlers;
这是存储库:
@Repository
public interface HotelRepository extends JpaRepository<Hotel, Long> {
public Optional<Hotel> findByTextAndSource(String text, String source);
}
实现如下所示:
@Service
public class MyService implements CrawlerService {
@Autowired
DocumentService documentService;
@Autowired
HotelRepository hotelRepository;
private Logger logger = LoggerFactory.getLogger("MyService");
private Set<String> visitedLinks = new HashSet<>();
@Override
public void start() {
execute("https://www.example.com/");
}
public void execute(String url) {
if(visitedLinks.contains(url))
return;
try {
logger.info("Connecting '{}' ...", url);
visitedLinks.add(url);
Document document = Jsoup.connect(url).get();
String text = documentService.getText(document);
// this is where I access to the database
if(hotelRepository.findByTextAndSource(text, "EXAMPLE").isPresent()) {
return;
}
Hotel hotel = new Hotel();
hotel.setUrl(url);
hotel.setText(text);
hotel.setSource("EXAMPLE");
hotelRepository.save(hotel);
// find other links
findLinks(document, url).forEach(this::execute);
} catch (IOException e) {
logger.error("Connection error for {}", url);
}
}
}
现在,我使用并行流并行运行它们中的每一个:
crawlers.stream().parallel().forEach(CrawlerService::start);
他们继续工作,直到希望通过JPA存储库访问数据库为止。然后,除分配给主线程的线程外,所有线程都停止。这是使用我的记录器的输出观察到的:
2018-11-01 21:42:38.408 INFO 7641 --- [ main] MyService ...
只有这一个继续运行
我希望他们继续并行工作。我怎样才能解决这个问题
值得一提的是,我正在使用MySQL和SpringBoot2,并对连接池进行默认设置
共 (0) 个答案