[Java/Spring] Server to Server (API GET)

Hyeri Park·2022년 8월 9일
0

JAVA/Spring 기초

목록 보기
17/22
post-thumbnail
post-custom-banner

Rest Template 사용

Server(Client)와 Server간의 통신

Spring에서 가장 많이 사용하는 'Rest Template'

1. 기본 작업

1) Client

(1) Apicontroller.java

package com.example.client.controller;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.client.service.RestTemplateService;

@RestController
@RequestMapping("/api/client")
public class ApiController {
	
	
	//@Autowired
	private final RestTemplateService restTemplateService;
	
	
	
	public ApiController(RestTemplateService restTemplateService) {

		this.restTemplateService = restTemplateService;
	}



	@GetMapping("/hello")
	public String getHello() {
		 return restTemplateService.hello();
	}
}

(2) RestTemplateService.java

package com.example.client.service;

import java.net.URI;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

@Service
public class RestTemplateService {
	
	// http://localhost/api/server/hello
	//response
	public String hello() {
		
		URI uri = UriComponentsBuilder
				.fromUriString("http://localhost:9090")
				.path("/api/server/hello")
				.encode()
				.build()
				.toUri();
				
		System.out.println(uri.toString());
		
		RestTemplate restTemplate = new RestTemplate();
		//String result = restTemplate.getForObject(uri, String.class);
		
		ResponseEntity<String> result = restTemplate.getForEntity(uri, String.class);
		
		System.out.println(result.getStatusCode());
		System.out.println(result.getBody());
		//return result;
		return result.getBody();
	};
}

2) server

(1) ServerApiController.java

package com.example.server.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

	@GetMapping("/hello")
	public String hello() {
		return "hello server";
	}
}



서버를 두대를 올린 후 !


(2) Json 형태로 리턴받기

1) Client

(1) ApiController.java

package com.example.client.controller;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.client.model.UserResponseDto;
import com.example.client.service.RestTemplateService;

@RestController
@RequestMapping("/api/client")
public class ApiController {
	
	
	//@Autowired //옛날에는 Autowired를 사용했는데, 요즘엔 생성자 주입방식으로 아래와 같이 사용한다.
	// default 생성자 = final 
	private final RestTemplateService restTemplateService;
	
	
	
	public ApiController(RestTemplateService restTemplateService) {

		this.restTemplateService = restTemplateService;
	}


	// 객체를 받아 전달 -> Dto 필요 
	@GetMapping("/hello")
	public UserResponseDto getHello() {
		 return restTemplateService.hello();
	}
}

(2) UserResponseDto.java

package com.example.client.model;

import lombok.Data;

@Data
public class UserResponseDto {
	private String name;
	private int age;
}

(3) RestTemplateService.java

package com.example.client.service;

import java.net.URI;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.example.client.model.UserResponseDto;

@Service
public class RestTemplateService {
	
	// http://localhost/api/server/hello
	//response
	//public String hello() {
	public UserResponseDto hello() {	
		URI uri = UriComponentsBuilder
				.fromUriString("http://localhost:9090")
				.path("/api/server/hello")
				.encode()
				.build()
				.toUri();
				
		System.out.println(uri.toString());
		
		RestTemplate restTemplate = new RestTemplate();
		// 결과를 only string으로 받을거야! 
		//String result = restTemplate.getForObject(uri, String.class);
		
		//(1) String 경우 
		//ResponseEntity<String> result = restTemplate.getForEntity(uri, String.class);
		
		//(2) dto를 받은경우  
		ResponseEntity<UserResponseDto> result = restTemplate.getForEntity(uri, UserResponseDto.class);
		
		
		System.out.println(result.getStatusCode());
		System.out.println(result.getBody());
		//return result;
		return result.getBody();
	};
}

2) Server

(1) ServerApiController.java

package com.example.server.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.server.model.UserDto;

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

	@GetMapping("/hello")
	//public String hello() {
	public UserDto hello() {
    
		UserDto user = new UserDto();
		user.setName("ila");
		user.setAge(31);
			
		return user;

	}
}

(2) UserDto.java

package com.example.server.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
//모든 매개변수 받음 
@AllArgsConstructor
public class UserDto {
	private String name;
	private int age;
}

실행

(3) 클라이언트 쪽에서 파라미터 받아서 실행 (@QueryParam)

아래의 2개의 스크립트만 수정하면 된다.

1) Client

(1) RestTemplateService.java

package com.example.client.service;

import java.net.URI;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.example.client.model.UserResponseDto;

@Service
public class RestTemplateService {
	
	// http://localhost/api/server/hello
	//response
	//public String hello() {
	public UserResponseDto hello() {	
		URI uri = UriComponentsBuilder
				.fromUriString("http://localhost:9090")
				.path("/api/server/hello")
			// client에서 queryParam에 값을 넣게 되는 경우 
				.queryParam("name","i am")
				.queryParam("age","21")
				.encode()
				.build()
				.toUri();
				
		System.out.println(uri.toString());
		
		RestTemplate restTemplate = new RestTemplate();
		// 결과를 only string으로 받을거야! 
		//String result = restTemplate.getForObject(uri, String.class);
		
		//(1) String 경우 
		//ResponseEntity<String> result = restTemplate.getForEntity(uri, String.class);
		
		//(2) dto를 받은경우  
		ResponseEntity<UserResponseDto> result = restTemplate.getForEntity(uri, UserResponseDto.class);
		
		
		System.out.println(result.getStatusCode());
		System.out.println(result.getBody());
		//return result;
		return result.getBody();
	};
}

2) Server

(1) ServerApiController.java

package com.example.server.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.server.model.UserDto;

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

	@GetMapping("/hello")

	// 전달된 값을 받아 사용할때!
	public UserDto hello(@RequestParam String name, @RequestParam int age) {
		UserDto user = new UserDto();
		
		user.setName(name);
		user.setAge(age);
		
		return user;
	}
}

서버 재 실행


profile
Backend Developer
post-custom-banner

0개의 댓글