Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ dependencies {
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
implementation 'org.springframework.boot:spring-boot-starter-webflux'

// swagger
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.1.0'
Expand Down
36 changes: 36 additions & 0 deletions src/main/java/com/example/umc7th/global/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.example.umc7th.global.config;

import java.time.Duration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

@Configuration
@Slf4j
public class WebConfig {

@Bean
public WebClient webClient() {
// 연결 설정
// TCP 연결 시 응답 시간 초과 값을 설정
HttpClient httpClient = HttpClient.create()
.responseTimeout(Duration.ofMillis(20000));

// WebClient 생성
return WebClient.builder()
// Base URL 설정
.baseUrl("https://apis.data.go.kr/B551011/KorService1")
// 만들었던 연결 설정 넣어주기
.clientConnector(new ReactorClientHttpConnector(httpClient))
// filter를 사용해서 요청을 보낼 때 로그가 찍히도록
.filter((request, next) -> {
log.info("Web Client Request: " + request.url());
return next.exchange(request);
})
// build로 객체 생성
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.example.umc7th.openAPI;

import org.springframework.web.reactive.function.client.WebClient;

public interface OpenApiWebClient {
WebClient getKoreanTourWebClient();
}
38 changes: 38 additions & 0 deletions src/main/java/com/example/umc7th/openAPI/OpenApiWebClientImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.example.umc7th.openAPI;

import java.time.Duration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.DefaultUriBuilderFactory;
import reactor.netty.http.client.HttpClient;

@Component
@Slf4j
public class OpenApiWebClientImpl implements OpenApiWebClient {
@Override
public WebClient getKoreanTourWebClient() {
return getWebClient("https://apis.data.go.kr/B551011/KorService1");
}

private WebClient getWebClient(String baseUrl) {
HttpClient httpClient = HttpClient.create()
.responseTimeout(Duration.ofMillis(20000));

// Uri를 build하는 factory 생성 (baseUrl을 WebClient 대신 여기에 포함하도록)
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(baseUrl);
// Uri factory에 인코딩 모드를 NONE으로 바꾸어 인코딩하지 않도록해줍니다.
factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);

return WebClient.builder()
.uriBuilderFactory(factory)
.clientConnector(new ReactorClientHttpConnector(httpClient))
.filter((request, next) -> {
log.info("Web Client Request: " + request.url());
return next.exchange(request);
})
.build();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.example.umc7th.openAPI.controller;

import com.example.umc7th.global.apiPayload.CustomResponse;
import com.example.umc7th.openAPI.dto.OpenApiResponseDTO.SearchStayResponseListDTO;
import com.example.umc7th.openAPI.service.OpenApiQueryServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class OpenApiController {

private final OpenApiQueryServiceImpl openApiQueryService;

@GetMapping("/searchStay")
public CustomResponse<SearchStayResponseListDTO> controller(
@RequestParam(name = "arrange", defaultValue = "A") String arrange,
@RequestParam(name = "page", defaultValue = "1") int page,
@RequestParam(name = "offset", defaultValue = "10") int offset) {
return CustomResponse.onSuccess(openApiQueryService.searchStay(arrange, page, offset));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.example.umc7th.openAPI.dto;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

public class OpenApiResponseDTO {
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Getter
// 해당 어노테이션으로 json 값을 Parsing할 때 필드가 없는 경우 무시하여 에러가 터지는 것을 방지, 한번 없이 돌려보시면 이해가 더 잘 되실겁니다.
@JsonIgnoreProperties(ignoreUnknown = true)
public static class SearchStayResponseDTO {
// 아래 변수는 Api 명세서의 응답을 보고 그대로 받고 싶은 값들만 똑같은 이름으로 만들어줍니다.
private String addr1;
private String title;
private String tel;
private String contentid;
private String contenttypeid;
private String createdtime;
private String firstimage;
private String firstimage2;
private String mapx;
private String mapy;
}

@Builder
@NoArgsConstructor
@AllArgsConstructor
@Getter
public static class SearchStayResponseListDTO {
private List<SearchStayResponseDTO> item;

public static SearchStayResponseListDTO from(List<SearchStayResponseDTO> list) {
return SearchStayResponseListDTO.builder()
.item(list)
.build();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package com.example.umc7th.openAPI.service;

import com.example.umc7th.openAPI.OpenApiWebClient;
import com.example.umc7th.openAPI.dto.OpenApiResponseDTO;
import com.example.umc7th.openAPI.dto.OpenApiResponseDTO.SearchStayResponseDTO;
import com.example.umc7th.openAPI.dto.OpenApiResponseDTO.SearchStayResponseListDTO;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Slf4j
@Service
@RequiredArgsConstructor
public class OpenApiQueryServiceImpl {

// WebClient를 가져오기 위한 빈 주입
private final OpenApiWebClient openApiWebClient;

@Value("${openapi.tour.serviceKey}")
private String serviceKey; // 인증 키

public OpenApiResponseDTO.SearchStayResponseListDTO searchStay(String arrange, int page, int offset) {
// Web Client 가져오기
WebClient webClient = openApiWebClient.getKoreanTourWebClient();
Mono<SearchStayResponseListDTO> mono = webClient.get() // get method 사용
// UriBuilder를 이용하여 Endpoint와 Query Param 설정
.uri(uri -> uri
.path("/searchStay1")
.queryParam("numOfRows", offset)
.queryParam("pageNo", page)
.queryParam("MobileOS", "ETC")
.queryParam("MobileApp", "AppTest")
.queryParam("_type", "json")
.queryParam("arrange", arrange)
.queryParam("serviceKey", serviceKey)
.build())
// 응답을 가져오기 위한 method (.onStatus()를 이용해서 Http 상태코드에 따라 다르게 처리해줄 수 있음)
.retrieve()
// 응답에서 body만 String 타입으로 가져오기 (ResponseEntity<Object> 중 Object만 String 형식으로 가져오기)
.bodyToMono(String.class)
// String 값을 메소드로 매핑하여 OpenApiResponseDTO.SearchStayResponseListDTO로 변경하기
.map(this::toSearchStayResponseListDTO)
// 에러가 발생한 경우 log를 찍도록
.doOnError(e -> log.error("Open Api 에러 발생: " + e.getMessage()))
// 성공한 경우에도 log를 찍도록
.doOnSuccess(s -> log.info("관광 정보를 가져오는데 성공했습니다."));

// block()을 사용해서 응답을 바로 가져오도록
return mono.block();
}

private OpenApiResponseDTO.SearchStayResponseListDTO toSearchStayResponseListDTO(String response) {
ObjectMapper objectMapper = new ObjectMapper();
try {
List<SearchStayResponseDTO> list = new ArrayList<>();
JsonNode jsonNode = objectMapper.readTree(response).path("response").path("body").path("items")
.path("item");
for (JsonNode node : jsonNode) {
list.add(objectMapper.convertValue(node, OpenApiResponseDTO.SearchStayResponseDTO.class));
}
return OpenApiResponseDTO.SearchStayResponseListDTO.from(list);
} catch (Exception e) {
e.fillInStackTrace();
}
return OpenApiResponseDTO.SearchStayResponseListDTO.from(null);
}

}