스프링 부트는 일반적인 REST 마이크로서비스의 작업을 추상화하고 개발자가 서비스 비즈니스 로직에 집중할 수 있게 한다. 스프링 부트로 간단한 Rest API, Hello world를 반환하는 프로젝트를 만들어 볼 것이다. 우선 스프링 부트 마이크로서비스의 작동 흐름을 보자.
다음과 같이 스프링 부트는 클라이언트 요청을 파싱하여 비즈니스 로직을 통해 결과를 반환한다. 상당히 복잡해 보일 수 도 있지만 간단한 예제를 통해 결과물을 산출해 낼 수 있다.
package com.tandohak.msa.springbootsimplemsa;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
@RequestMapping("/hello") // url에 /hello가 앞에 붙는다.
@RestController // 이 클래스의 코드를 스프링 RestController 클래스로 노출하도록 지정
@SpringBootApplication // 스프링 부트 프레임워크에 이 클래스가 스프링 부트 서비스 진입점
// 이라고 지정한다.
public class SpringBootSimpleMsaApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSimpleMsaApplication.class, args);
}
// 두개의 매개 변수인 firstName과 lastName을 hello 함수의 두변수에 매핑한다.
@GetMapping("/{firstName}/{lastName}")
public ResponseEntity<?> hello(@PathVariable String firstName, @PathVariable String lastName) {
// HashMap을 통해 간단한 결과 값을 작성 후 반환한다.
HashMap<String, String> result = new HashMap<>();
result.put("message", String.format("Hello %s %s", firstName, lastName));
return ResponseEntity.ok(result);
}
}
요청시 다음과 같이 결과가 반환된다.
정말 간단한 Spring boot 프로젝트로 Rest Api 서버를 구축해 보았다. 이 예제는 스프링 부트는 정말 간단한 코드 몇 줄로 HTTP JSON REST 기반 서비스를 쉽고 빠르게 작성할 수 있다는 것을 알려준다. 책의 다음 챕터를 보고 애플리케이션 구축 방식을 마이크로서비스 방식으로 바꾸는 이유에 대해 알아보고 MSA와 클라우드에 대해 공부 할 것이다.
스프링 마이크로 서비스 공작소 저자 [존 카넬] - 길벗 출판사