이번에 따라가 볼 가이드는 RESTful 웹 서비스 사용하기! 입니다.
이 가이드는 RESTful 웹 서비스를 사용하는 application 생성 프로세스를 따릅니다.
우리가 만들 application
Spring의 RestTeamplate를 사용해
https://gturnquist-quoters.cfapps.io/api/random
위 API에서 무언가를 검색하는 application을 만들겠습니다.
준비 사항
- 약 15분의 시간
- JDK 1.8 이상의 버전
- Gradle 4+ 혹은 Maven 3.2+
- 가장 선호하는 IDE (우리는 vscode를 사용할게요!)
Spring Initializr
이전에 따라한 것과 같이 https://start.spring.io/ 에 접속하여 하단에 의존성을 web만 선택하시고 생성 해주시면 되겠습니다!
파란색 동그라미를 따라 오시게 되면 최 하단에 다운로드가 진행 되는 모습을 볼 수 있습니다!
다운로드 된 폴더로 들어가셔서 압축을 해제하고 나신 뒤 자주 사용하시는 애디터로 다운받은 프로젝트를 열어 주시면 됩니다!
만약 Spring Initializr로 다운로드한 프로젝트가 org.springframework~~~로 시작하는 패키지를 불러올 수 없다고 한다면... 많이 골치 아프실 거에요. 하지만 걱정마세요! 이런 현상을 해결할 수 있는 방법이 두 가지 있습니다.
1. 물리적인 해결방법
- 물리적인 해결방법은 간단합니다! 이전에 Spring Initializr로 프로젝트를 생성하고 기억했던 다른 프로젝트의 캐시를 날려주는겁니다!
- C:\Users\username\AppData\Roaming\Code로 들어가시게 되면 cache관련된 폴더가 있습니다. cache/cached Data 폴더를 삭제해주시면 됩니다! 그러면 관련된 데이터가 삭제되고 다시 현제 진행하는 프로젝트의 빌드를 사용할 수 있습니다.
2. vscode 안에서 해결방법
- 먼저 vscode 안에 탐색기에서 Spring-boot-dashboard를 찾아줍니다.
- 실행할 수 있는 프로젝트가 보이죠? 재생 모양의 버튼을 눌러줍니다.
- 오류가 발생한 상황에서 왜 실행을 누르냐구요? 우측 하단을 봐주세요
- 우측 하단에 000-Fix-000 이렇게 오류를 해결할 수 있는 버튼이 팝업창에 보여지게 됩니다.
- fix를 누르시고 중앙 상단에 보이시는 clean workspace cache를 눌러주세요.
- 마지막으로 vscode를 닫았다가 다시 실행하시면 빌드를 다시하고 오류가 해결한 모습을 볼 수 있습니다.
REST Resource 가지고 오기!
프로젝트의 설정과 세팅이 끝났다면, 이제 간단한 application을 만들 준비가 되어있습니다.
https://gturnquist-quoters.cfapps.io/api/random
위의 링크를 접속하여 보시면 우리가 불러올 RESTful 서비스가 어떻게 보여지는지 확인하실 수 있습니다.
접속된 화면은 URL이나 CURL로 요청을 보내면 클라이언트가 받는 JSON document입니다.
REST 웹 서비스를 더 유용하게 사용하는 방법은 프로그래밍 입니다. RESTful 웹서비스를 구축하는 과정에서 스프링은 RestTemplate라고 불리는 편리한 템플릿 클래스를 제공합니다. RestTemplate는 스프링에서 제공하는 http 통신에 유용하게 쓸 수 있는 템플릿이며, HTTP 서버와의 통신을 단순화하고 RESTful 원칙을 지킵니다. jdbcTemplate 처럼 RestTemplate 도 기계적이고 반복적인 코드들을 깔끔하게 정리해줍니다.
RestTemplate에 대해서 자세하게 이해하고 싶으시다면 아래 링크를 참조해 주세요!
https://sjh836.tistory.com/141
RestTemplate (정의, 특징, URLConnection, HttpClient, 동작원리, 사용법, connection pool 적용)
참조문서 : https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html 1. RestTemplate이란? spring 3.0 부터 지원한다. 스프링에서 제공하는 http..
sjh836.tistory.com
자, 먼저 필요한 데이터를 포함할 VO 클래스를 작성하겠습니다. 아래의 코드는 VO클래스로 사용할 수 있는 가장 좋은 예입니다.
src/main/java/com/example/consumingrest 폴더에 파일을 하나 만드시고 Quote.java라고 작성해 주세요.
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type;
private Value value;
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
@Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}
위의 클래스는 type과 value라는 이름으로 getter/setter 그리고 toSrting()메소드를 가지고 있습니다.
@JsonIgnoreProperties 어노테이션은 위 클래스에서 명시하지 않은 속성은 무시하는 기능을 가지고 있습니다.
데이터를 사용자 지정 유형에 직접 바인딩하려면 API에서 반환된 Json document의 Key와 정확하게 일치하도록 변수 이름을 지정해야 합니다. 만약에 일치하지 않는 경우 @JsonProperty 주석을 사용하여 Json document에 정확한 key를 지정할 수 있습니다.
또한 위의 변수타입인 value는 아직 없어 클래스를 작성해줘야 합니다.
같은 위치에 Value.java 클래스를 생성하여 아래와 같이 작성해 줍니다.
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Value {
private Long id;
private String quote;
public Value() {
}
public Long getId() {
return this.id;
}
public String getQuote() {
return this.quote;
}
public void setId(Long id) {
this.id = id;
}
public void setQuote(String quote) {
this.quote = quote;
}
@Override
public String toString() {
return "Value{" +
"id=" + id +
", quote='" + quote + '\'' +
'}';
}
}
위의 Value.java 클래스는 동일한 VO 클래스 형식과 어노테이션을 사용하지만, 다른 데이터 필드를 매핑합니다.
Application 완성하기
처음에 작성을 할 때 Main() 메소드가 자동으로 생성 되었습니다. 제대로 따라 하셨다면 그 소스는 패키지 명만 다르고 아래와 동일합니다.
package com.example.consumingrest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ConsumingRestApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumingRestApplication.class, args);
}
}
이제 여기서 몇 가지를 더 작성하겠습니다!
- log에 출력을 전송하는 logger.
- 수신 데이터를 처리하기 위해 Jackson JSON 처리 라이브러리를 사용하는 RestTemplate.
- 시작 시 RestTemplate를 실행하는 CommandLineRunner.
세 가지를 적용하셨다면 아래 코드와 같은 형식이 되어 있을 겁니다.
package com.example.consumingrest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class ConsumingRestApplication {
private static final Logger log = LoggerFactory.getLogger(ConsumingRestApplication.class);
public static void main(String[] args) {
SpringApplication.run(ConsumingRestApplication.class, args);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
Quote quote = restTemplate.getForObject(
"https://gturnquist-quoters.cfapps.io/api/random", Quote.class);
log.info(quote.toString());
};
}
}
Application 실행
Gradle 또는 Maven로 Command에서 애플리케이션을 실행할 수 있습니다. 또한 필요한 모든 종속성, 클래스 및 리소스를 포함하는 단일 실행 파일 JAR 파일을 구축하고 이를 실행할 수 있습니다. 실행 가능한 jar를 구축하면 개발 생명주기 전체에 걸쳐, 서로 다른 환경 등에 걸쳐 애플리케이션으로서 서비스를 쉽게 버전관리 및 배포할 수 있다.
Gradle을 사용하는 경우 ./gradlew bootRun을 사용하여 응용 프로그램을 실행할 수 있습니다. 또는 ./gradlew 빌드를 사용하여 JAR 파일을 생성한 다음 다음과 같이 JAR 파일을 실행할 수 있습니다.
java -jar build/libs/gs-consuming-rest-0.1.0.jar
Maven을 사용하신다면, ./spring-boot:run을 입력하여 실행하실 수 있습니다. 또는 ./mvnw 클린 패키지로 JAR 파일을 생성한 다음 다음과 같이 JAR 파일을 실행할 수 있습니다.
java -jar target/gs-consuming-rest-0.1.0.jar
실행을 하셨다면 다음과 같은 결과를 보게됩니다.
2019-08-22 14:06:46.506 INFO 42940 --- [ main] c.e.c.ConsumingRestApplication : Quote{type='success', value=Value{id=1, quote='Working with Spring Boot is like pair-programming with the Spring developers.'}}
'IT > Back-end' 카테고리의 다른 글
서버 기동시 port 중복 해결방법! (2) | 2020.03.18 |
---|---|
REST 방식으로 JPA Data에 접근하기 (0) | 2020.03.10 |
[Spring] 데이터에 접근하기 (feat. JPA) -(1) (0) | 2020.03.10 |
RESTful Web Service 구축하기! (feat. spring)-(2) (0) | 2020.03.03 |
RESTful Web Service 구축하기! (feat. spring)-(1) (0) | 2020.03.03 |