1. 구조 및 포트 할당
- MyRestServer : 8180 포트
- MyRestClient : 8888 포트
2. 코드
Server App, Client App 2개를 생성한다.
2.1. MyRestServer
package io.sarc.springcloud.MyRestServer; import java.util.Arrays; import java.util.List; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class MyRestServerApplication { private static Logger log = LoggerFactory.getLogger(MyRestServerApplication.class); @RequestMapping(value = "/greeting") public String greet() { log.info("Access /greeting"); List<String> greetings = Arrays.asList("Hi", "Hello", "Greetings"); Random rand = new Random(); int randomNum = rand.nextInt(greetings.size()); return greetings.get(randomNum); } public static void main(String[] args) { SpringApplication.run(MyRestServerApplication.class, args); } }
application.yml
spring: application: name: my-rest-server server: port: 8180
2.2. MyRestClient
package io.sarc.springcloud.MyRestClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @SpringBootApplication @RestController public class MyRestClientApplication { @Bean RestTemplate restTemplate() { return new RestTemplate(); } @Autowired RestTemplate restTemplate; public static void main(String[] args) { SpringApplication.run(MyRestClientApplication.class, args); } @RequestMapping("/hello") public String hello(@RequestParam(value="name", defaultValue="sarc.io") String name) { String greeting = this.restTemplate.getForObject("http://localhost:8180/greeting", String.class); return String.format("Hello from '%s %s'!", greeting, name); } }
application.yml
spring: application: name: my-rest-client server: port: 8888
7.3. REST 테스트
$ curl http://localhost:8888/hello Hello from 'Hi sarc.io'! $ curl http://localhost:8888/hello Hello from 'Greetings sarc.io'! $ curl http://localhost:8888/hello?name=Seoul Hello from 'Greetings Seoul'!