[Spring] RestTemplate 사용(Server 간 연결)

WOOK JONG KIM·2022년 11월 15일
0

패캠_java&Spring

목록 보기
47/103
post-thumbnail

Client

UserRequest와 UserResponse는 String name, int age로 구성

Req< T >

public class Req<T> {

    private Header header;

    private T responseBody;
    public static class Header{

        private String responseCode;

        public String getResponseCode() {
            return responseCode;
        }

        public void setResponseCode(String responseCode) {
            this.responseCode = responseCode;
        }

        @Override
        public String toString() {
            return "Header{" +
                    "responseCode='" + responseCode + '\'' +
                    '}';
        }
    }

    public void setHeader(Header header) {
        this.header = header;
    }

    public Header getHeader() {
        return header;
    }

    public T getResponseBody() {
        return responseBody;
    }

    public void setResponseBody(T responseBody) {
        this.responseBody = responseBody;
    }

    @Override
    public String toString() {
        return "Req{" +
                "body=" + responseBody +
                '}';
    }
}

컨트롤러

@RestController
@RequestMapping("/api/client")
public class ApiController {

   private final RestTemplateService restTemplateService;

   public ApiController(RestTemplateService restTemplateService) {
       this.restTemplateService = restTemplateService;
   }

   @GetMapping("/hello")
   public Req<UserResponse> getHello(){
       return restTemplateService.genericExchange();
   }

}

서비스

@Service
public class RestTemplateService {

public Req<UserResponse> genericExchange(){
        URI uri = UriComponentsBuilder.fromUriString("http://localhost:9090")
                .path("/api/server/user/{userId}/name/{userName}")
                .encode()
                .build()
                .expand(100,"steve")
                .toUri();
        System.out.println(uri);


        // http body -> object -> object mapper -> json -> rest template -> http body json
        UserRequest userRequest = new UserRequest();
        userRequest.setName("steve");
        userRequest.setAge(10);

        Req<UserRequest> req = new Req<UserRequest>();
        req.setHeader(
                new Req.Header()
        );
        req.setResponseBody(
                userRequest
        );



        RequestEntity<Req<UserRequest>> requestEntity = RequestEntity
                .post(uri)
                .contentType(MediaType.APPLICATION_JSON)
                .header("x-authorization", "abcd")
                .header("custom-header", "ffff")
                .body(req);

        RestTemplate restTemplate = new RestTemplate();

        // 제네릭은 .class 못 붙임



        ResponseEntity<Req<UserResponse>> response =
                restTemplate.exchange(requestEntity,
                        new ParameterizedTypeReference<Req<UserResponse>>(){});


        return response.getBody();

    }
}

서버

Req

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Req<T> {

    private Header header;
    private T responseBody;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Header{
        private String responseCode;
    }
}

User는 String name, int age

컨트롤러

@RestController
@Slf4j
@RequestMapping("/api/server")
public class ServerApiController {

@PostMapping("/user/{userId}/name/{userName}")
    public Req<User> post(
                    // HttpEntity<String> entity,
                    @RequestBody Req<User> user,
                    @PathVariable int userId, @PathVariable String userName,
                    @RequestHeader("x-authorization") String authorization,
                     @RequestHeader("custom-header") String customHeader){
       //  log.info("req : {}", entity.getBody());
        log.info("userId : {}, userName : {}", userId, userName);
        log.info("authorziation : {}, custom:{}", authorization, customHeader);
       log.info("client req : {}", user);

        Req<User> response = new Req<>();
        response.setHeader(
                new Req.Header()
        );
        response.setResponseBody(user.getResponseBody());

        return response;
    }
}
profile
Journey for Backend Developer

0개의 댓글