다른 서버에 REST요청하기
build.gradle
implementation 'org.apache.httpcomponents:httpclient:4.5'
implementation 'com.google.code.gson:gson:2.8.5'
이 경우 spring이 client와 같은 역할이 되므로 위의 라이브러리를 설치.
application.yml
restTemplate:
factory:
readTimeout: 5000
connectTimeout: 3000
httpClient:
maxConnTotal: 100
maxConnPerRoute: 5
RestfulCofig 클래스
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* 다른 서버에 Rest요청을 할 때 필요한 설정을 해주는 클래스
*/
@Configuration
public class RestfulConfig {
@Value("${restTemplate.factory.readTimeout}")
private int READ_TIMEOUT;
@Value("${restTemplate.factory.connectTimeout}")
private int CONNECT_TIMEOUT;
@Value("${restTemplate.httpClient.maxConnTotal}")
private int MAX_CONN_TOTAL;
@Value("${restTemplate.httpClient.maxConnPerRoute}")
private int MAX_CONN_PER_ROUTE;
@Bean
public RestTemplate restTemplate() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setReadTimeout(READ_TIMEOUT);
factory.setConnectTimeout(CONNECT_TIMEOUT);
HttpClient httpClient = HttpClientBuilder.create()
.setMaxConnTotal(MAX_CONN_TOTAL)
.setMaxConnPerRoute(MAX_CONN_PER_ROUTE)
.build();
factory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(factory);
return restTemplate;
}
}
사용하는 부분
public String Request(){
String jsonStr = restTemplate.getForObject("http://172.27.106.250/", String.class);
Gson gson = new Gson();
List<CurrentVO> list = gson.fromJson(jsonStr, new TypeToken<List<CurrentVO>>(){}.getType());
return "리스트에서 10번째의 값: "+ list.get(10).value;
}
Request 참고: https://4urdev.tistory.com/58
JSON 리스트를 객채로 파싱 참고: https://jekalmin.tistory.com/entry/Gson%EC%9D%84-%EC%9D%B4%EC%9A%A9%ED%95%9C-json%EC%9D%84-%EA%B0%9D%EC%B2%B4%EC%97%90-%EB%8B%B4%EA%B8%B0
'Spring boot' 카테고리의 다른 글
@Data, @Getter, @Setter 가 제대로 작동하지 않을 때 (0) | 2019.07.23 |
---|---|
Controller에서 GET방식으로 parameter 여러개 받기 (0) | 2019.07.19 |
Application을 시작하자마자 저절로 끝나버릴 때 (0) | 2019.07.12 |
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured. (0) | 2019.07.11 |
Spring boot 기초 (0) | 2019.07.11 |