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
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ dependencies {

// OAuth2 login
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'

// WebFlux
implementation 'org.springframework.boot:spring-boot-starter-webflux'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
public enum MemberErrorCode implements BaseErrorCode {

NOT_FOUND(HttpStatus.NOT_FOUND, "MEMBER404", "멤버를 찾지 못했습니다."),
ALREADY_EXIST(HttpStatus.BAD_REQUEST, "MEMBER400", "이미 존재하는 사용자입니다."),
INCORRECT_PASSWORD(HttpStatus.UNAUTHORIZED, "MEMBER401", "비밀번호가 틀립니다."),
EXIST_EMAIL(HttpStatus.CONFLICT,
"MEMBER409",
"이미 사용중인 이메일입니다."),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.example.umc7th.global.apiPayload.code;

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.http.HttpStatus;

@AllArgsConstructor
@Getter
public enum OpenApiErrorCode implements BaseErrorCode {

UNSUPPORTED_LANGUAGE(HttpStatus.NOT_FOUND, "OPENAPI400", "제공하지 않는 언어입니다.");

private final HttpStatus status;
private final String code;
private final String message;
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.example.umc7th.global.apiPayload.exception;

import com.example.umc7th.global.apiPayload.code.BaseErrorCode;
import lombok.Getter;

@Getter
public class OpenApiException extends RuntimeException {

private final BaseErrorCode code;

public OpenApiException(BaseErrorCode code) {
this.code = code;
}
}
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.example.umc7th.global.web.client;

import com.example.umc7th.global.apiPayload.exception.OpenApiException;
import org.springframework.web.reactive.function.client.WebClient;

public interface OpenApiWebClient {

// 한국 관광정보를 가져올 수 있는 WebClient를 반환하는 메소드 정의

WebClient getTourWebClient(String language) throws OpenApiException;
// 아래에 메소드를 추가하면서 확장해나갈 수 있겠죠?
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.example.umc7th.global.web.client;

import com.example.umc7th.global.apiPayload.code.OpenApiErrorCode;
import com.example.umc7th.global.apiPayload.exception.OpenApiException;
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;

import java.time.Duration;

@Component
@Slf4j
public class OpenApiWebClientImpl implements OpenApiWebClient {

@Override
public WebClient getTourWebClient(String language) {
if (language.equals("korean")) {
return getWebClient("https://apis.data.go.kr/B551011/KorService1");
} else if (language.equals("english")) {
return getWebClient("https://apis.data.go.kr/B551011/EngService1");
} else {
throw new OpenApiException(OpenApiErrorCode.UNSUPPORTED_LANGUAGE);
}
}

// 영문 API를 추가한 경우
// @Override
// public WebClient getEnglishTourWebClient() {
// return getWebClient("https://apis.data.go.kr/B551011/EngService1");
// }

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.global.web.controller;

import com.example.umc7th.global.apiPayload.CustomResponse;
import com.example.umc7th.global.web.dto.OpenApiResponseDTO;
import com.example.umc7th.global.web.service.OpenApiQueryService;
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 OpenApiQueryService openApiQueryService;

@GetMapping("/searchStay")
public CustomResponse<OpenApiResponseDTO.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,47 @@
package com.example.umc7th.global.web.dto;

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

import java.util.List;

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,8 @@
package com.example.umc7th.global.web.service;

import com.example.umc7th.global.web.dto.OpenApiResponseDTO;

public interface OpenApiQueryService {

OpenApiResponseDTO.SearchStayResponseListDTO searchStay(String arrange, int page, int offset);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package com.example.umc7th.global.web.service;

import com.example.umc7th.global.web.client.OpenApiWebClient;
import com.example.umc7th.global.web.dto.OpenApiResponseDTO;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class OpenApiQueryServiceImpl implements OpenApiQueryService {

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

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

@Override
public OpenApiResponseDTO.SearchStayResponseListDTO searchStay(String arrange, int page, int offset) {
// Web Client 가져오기
WebClient webClient = openApiWebClient.getTourWebClient("korean");
Mono<OpenApiResponseDTO.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 {
// item으로 담을 list 선언
List<OpenApiResponseDTO.SearchStayResponseDTO> list = new ArrayList<>();
// JsonNode 형식으로 응답을 읽고 item이 담긴 배열만 읽고 싶기에 item이 있는 배열까지 들어가기
JsonNode jsonNode = objectMapper.readTree(response).path("response").path("body").path("items").path("item");
// item 하나씩 처리
for (JsonNode node : jsonNode) {
// item 하나씩 읽어서 OpenApiResponseDTO.SearchStayResponseDTO로 변경해서 List에 추가
list.add(objectMapper.convertValue(node, OpenApiResponseDTO.SearchStayResponseDTO.class));
}
// 응답을 만들어서 반환
return OpenApiResponseDTO.SearchStayResponseListDTO.from(list);
} catch (Exception e) {
// 에러 처리
e.fillInStackTrace();
}
return OpenApiResponseDTO.SearchStayResponseListDTO.from(null);
}

}
6 changes: 5 additions & 1 deletion src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,8 @@ Jwt:
secret: ${JWT_SECRET}
token:
access-expiration-time: 3600000 # Milliseconds for 1 hour
refresh-expiration-time: 2592000000 # Milliseconds for 30 days
refresh-expiration-time: 2592000000 # Milliseconds for 30 days

openapi:
tour:
serviceKey: ${SERVICE_KEY}