환경 : 오라클 클라우드 free... ram 1gb, vcpu2
OS : Linux centos7
DB : mariadb 10.5.8
Tool : 인텔리제이, Java 1.8
Spring boot 2.4.5 그래들 환경
스웨거
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation group: 'com.googlecode.log4jdbc', name: 'log4jdbc', version: '1.2' // SQL Log
implementation "io.springfox:springfox-boot-starter:3.0.0" //swagger
compile "io.springfox:springfox-swagger-ui:3.0.0" //swagger
// https://mvnrepository.com/artifact/org.apache.commons/commons-pool2
implementation group: 'org.apache.commons', name: 'commons-pool2', version: '2.9.0'
// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.6'
// https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client
implementation group: 'org.mariadb.jdbc', name: 'mariadb-java-client', version: '2.7.2'
// https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter
implementation group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '2.1.4'
build.gradle
기본 뼈대가 되는 구조.
exception : 원하는 Exception으로 서버에서 처리 시 throw 용도
loggin : 로그 찍기 위한 클래스.
request : request 들어오는 내용을 처리하려고 만듬. 현재 InterceptorController 인터럽트만 사용.
response : 전역오류 핸들링, 오류 메시지, 성공 오류 시 일정한 반환값을 위한 클래스가 존재.
util : Http 통신 클래스, Json 변환 클래스 등
실제 콘텐츠가 있는 정보.
@RestController
@RequestMapping(value = "/weather", produces = "application/json; charset=UTF-8")
@Api(value="weather-controller", description = "날씨 요청")
public class WeatherController {
private final IWeatherService weatherService;
@Autowired
public WeatherController(IWeatherService weatherService){
this.weatherService = weatherService;
}
@GetMapping(value = {"/code"})
@ApiOperation(value = "날씨 코드", notes = "날씨 코드를 요청한다.", response = WeatherCodeDto.class, responseContainer = "List")
public String selectWeatherCodeList(HttpServletRequest request) {
List<WeatherCodeDto> weatherCodeDtoList = weatherService.selectWeatherCodeList(null);
ResponseMessage message = new ResponseMessage();
message.add("weatherCodeList", weatherCodeDtoList);
return JsonConverter.convert(message);
}
@GetMapping(value = {"/code/{name}"})
@ApiOperation(value = "날씨 코드", notes = "날씨 코드를 요청한다.", response = WeatherCodeDto.class, responseContainer = "List")
public String selectWeatherCode(HttpServletRequest request, @PathVariable(value = "name", required = true) String name) {
List<WeatherCodeDto> weatherCodeDtoList = weatherService.selectWeatherCodeList(name);
ResponseMessage message = new ResponseMessage();
message.add("weatherCodeList", weatherCodeDtoList);
return JsonConverter.convert(message);
}
@PostMapping(value = "/list" )
@ApiOperation(value = "날씨 요청", notes = "날씨를 요청한다.", response = WeatherCodeDto.class, responseContainer = "List")
public String selectWeatherList(HttpServletRequest request
, @RequestParam(value = "x", required = true) int x
, @RequestParam(value = "y", required = true) int y) {
List<WeatherDto> weatherDtoList = weatherService.getWeatherData(x, y);
ResponseMessage message = new ResponseMessage();
message.add("weatherList", weatherDtoList);
return JsonConverter.convert(message);
}
}
@Service
public class IWeatherServiceImpl implements IWeatherService {
@Value("${data-api.end-point}")
private String dataApiEndPoint;
@Value("${data-api.enc-key}")
private String dataApiEncKey;
private final IWeather weather;
public IWeatherServiceImpl(IWeather weather) {
this.weather = weather;
}
@Override
public List<WeatherCodeDto> selectWeatherCodeList(String name) {
return weather.selectWeatherCodeList(name);
}
@Override
public List<WeatherDto> getWeatherData(int x, int y) {
Map<String, Object> map = new HashMap<>();
map.put("serviceKey", dataApiEncKey);
map.put("numOfRows", 200);
map.put("pageNo", 1);
map.put("nx", x);
map.put("ny", y);
/*map.put("base_date", getBaseDate());*/
map.put("base_date", Util.getYesterday(new Date()));
map.put("base_time", "2300");
/*map.put("base_time", getBaseTime());*/
map.put("dataType", "JSON");
List<WeatherDto> weatherDtoList = new ArrayList<>();
try {
String resultJson = HttpRequester.sendHttpGetWithParameters(dataApiEndPoint.concat("/getVilageFcst"), map);
WeatherDataDto weatherDataDto = JsonConverter.convertToClass(WeatherDataDto.class, resultJson);
WeatherDataDto.ResponseHeaderDto headerDto = weatherDataDto.getResponse().getHeader();
if(Integer.parseInt(headerDto.getResultCode()) > 0) {
throw new RestapiInvalidRequestException(CustomErrorCode.errorCode.DataApiException.getCode(), headerDto.getResultMsg());
}
List<WeatherDataDto.ResponseItemDto> responseItemDtoList = weatherDataDto.getResponse().getBody().getItems().getItem();
List<WeatherDataDto.ResponseItemDto> distinctItemDtoList = responseItemDtoList.stream()
.filter(Util.distinctByKeys(WeatherDataDto.ResponseItemDto::getFcstDate, WeatherDataDto.ResponseItemDto::getFcstTime)).distinct().collect(Collectors.toList());
for (WeatherDataDto.ResponseItemDto distinctItem : distinctItemDtoList) {
List<WeatherDataDto.ResponseItemDto> itemDtoList = responseItemDtoList.stream()
.filter(t -> t.getFcstDate().equals(distinctItem.getFcstDate()) && t.getFcstTime().equals(distinctItem.getFcstTime())).collect(Collectors.toList());
WeatherDto weatherDto = new WeatherDto();
weatherDto.setFcstTime(distinctItem.getFcstTime());
weatherDto.setFcstDate(distinctItem.getFcstDate());
//아침최저 온도는 06시, 낮 최고온도는 15시만 들어있음.
for(WeatherDataDto.ResponseItemDto item : itemDtoList) {
weatherDto.getItem().put(item.getCategory(), item.getFcstValue());
}
weatherDtoList.add(weatherDto);
}
} catch (RestapiInvalidRequestException ex) {
throw new RestapiInvalidRequestException(ex.getErrorCode(), ex.getMessage());
} catch (Exception ex) {
throw new RestapiInvalidRequestException(CustomErrorCode.errorCode.DataApiException.getCode(), CustomErrorMessage.errorMessage.DataApiException.getMessage());
}
return weatherDtoList;
}
private String getBaseDate() {
Date date = new Date();
int baseTimeNumber = Integer.parseInt(Util.getDateString("HH", date));
final int minTime = 2;
if (minTime > baseTimeNumber) {
return Util.getYesterday(date);
} else {
return Util.getDateString("yyyyMMdd", date);
}
}
private String getBaseTime() {
int resultTime = 2;
int baseTimeNumber = Integer.parseInt(Util.getDateString("HH", new Date()));
int[] baseTimeArray = { 2, 5, 8, 11, 14, 17, 20, 23 };
for(int i = 0; i < baseTimeArray.length; i++) {
if(baseTimeArray[i] == baseTimeNumber) {
resultTime = baseTimeArray[i];
break;
} else if(baseTimeArray[i] > baseTimeNumber) {
if(i == 0){
resultTime = 23;
} else {
resultTime = baseTimeArray[i - 1];
}
break;
}
}
return String.format("%02d", resultTime).concat("00");
}
}
'포트폴리오 > Java rest api' 카테고리의 다른 글
Reuters 환율 처리 (1) | 2022.11.18 |
---|---|
중계 서버 (0) | 2022.11.18 |
rest api filter에서 header, body 변경 (0) | 2022.09.07 |
rest api + jpa(jpql) + replica set (0) | 2022.08.02 |
Java 기본 Rest api (0) | 2020.08.11 |