Home > Back-end >  Spring multiple requests simultaneously
Spring multiple requests simultaneously

Time:04-24

This is the code that sends a POST request with the link data of each post after receiving the list of posts in db.

After requesting POST with each link, extract the playerCount from the response and update it to each post.

I am using Resttemplate in this code, but there is an issue that takes too long.

So I want to change this code to sending a request at once and update each post when all the requests are finished.

How can i convert this code to what i want ?

I'm going to use this code as a scheduled task.

    @Test
    @Transactional
    @Rollback(false)
    public void postToGraphql2() throws JsonProcessingException, JSONException {
        String URL = "https://gt-space-data.herokuapp.com/graphql";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("content-type", "application/json");

        long startTime = System.currentTimeMillis();

        List<Posts> list = postsRepository.findPostsByCategoryStringContaining("GATHERTOWN");
        String query = "query gameData($apikey:String!,$spaceid:String!,$spacename:String!){gameData(spaceData:{apiKey: $apikey, spaceIdNum: $spaceid, spaceName: $spacename}){playerCount,}}";
        String opertationName = "gameData";

        list.forEach(posts -> {
            String link = posts.getLink();
            if(link.contains("gather.town")){
                String spaceid = link.substring(link.indexOf("app/") 4,link.lastIndexOf("/"));
                String spacename = link.substring(link.lastIndexOf("/") 1, link.length());
                String variables = "{\"apikey\": \"QUNCVEQGILsqe5\",\"spaceid\": \"" spaceid "\",\"spacename\" : \"" spacename "\"}";

                try {
                    ResponseEntity<PlayerCountDto> response =
                            restTemplate.postForEntity(URL, new HttpEntity<>(createJsonQueries(query,opertationName,variables), headers), PlayerCountDto.class);
                    int playerCount = Objects.requireNonNull(response.getBody()).getData().getGameData().playerCount;
                    posts.setPlayerCount(playerCount);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
        });

        long stopTime = System.currentTimeMillis();
        long elapsedTime = stopTime - startTime;

        System.out.println(elapsedTime);
    }

CodePudding user response:

One way is to replace Resttemplate with 'Webclient'. Webclient is part of Spring Webflux introduced in Spring 5.0. Webclient is asynchronous and non-blocking.

You can start with following document

https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/html/boot-features-webclient.html

  • Related