일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- 아마존 서버 배포
- ssh권한
- 서버배포
- 스프링부트
- 자바
- 서버 배포
- 서버간통신
- Blockchain
- 철도
- linux
- 히가시큐슈신칸센
- 서버
- 신칸센
- 8200호대
- 스프링
- 아마존
- 동큐슈신칸센
- WSL
- EC2
- 철도소식
- Java
- tendermint
- AWS
- 일본철도
- remote PC
- 열차
- 스프링부트 배포
- 기차
- server to server
- vscode ssh
- Today
- Total
사진과 컴퓨터
[SpringBoot]Webclient를 이용해 Server to Server 통신 구현 본문
SpringBoot로 백앤드 개발중에 server to server 통신을 이용해 데이터를 주고받을 일이 생겼다.
찾아보니 WebClient방식과 RestTemplate방식이 있는데, RestTemplate방식의 경우
효율등의 문제를 이유로 WebClient 사용을 권장하고 있다고 한다.
따라서 WebClient로 구현해 보았다.
우선, 구현하고자 하는 시나리오는 다음과 같다.
1. A서버에서 유저 요청으로 DTO에 값을 담는다.
2. DTO에 값을 담은 A서버가 POST요청으로 B서버에 DTO를 전달한다.
3. DTO를 전달받은 B서버가 내용물을 본인 DB에 저장한다.
4. B서버에서 성공 리턴 해준다.
일단 값을 주고받을 객체 RTestDTO를 만든다.
RTestDTO
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
public class RTestDTO {
private String name;
private Long memberId;
private String guitar;
}
Server A(송신)측
Server A - Controller
@PostMapping(value = "/posttest")
public ResponseEntity<String> postTest() {
ResponseEntity<String> value = restTemplateService.postParamAndBody();
return ResponseEntity.ok(value.toString());
}
server A에서 유저로부터 요청을 받는 Controller이다.
WebClientService
public interface WebClientService {
ResponseEntity<String> postParamAndBody();
}
WebClientServiceImpl
@Service
@Log4j2
@RequiredArgsConstructor
@Transactional
@Data
public class WebClientServiceImpl implements WebClientService{
public ResponseEntity<String> postParamAndBody() {
WebClient webClient = WebClient.builder()
.baseUrl("http://localhost:8080")
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
RTestDTO rTestDTO = new RTestDTO();
rTestDTO.setName("name");
rTestDTO.setMemberId(10L);
rTestDTO.setGuitar("Guitar playing good");
return webClient.post().uri(uriBuilder -> uriBuilder.path("/report/rpost")
.build())
.bodyValue(rTestDTO)
.retrieve()
.toEntity(String.class)
.block();
}
}
RTestDTO에 hardcoding된 값들을 setting하고, 해당 DTO를 http://localhost의 /report/rpost로 요청을 보낸다. (body에 실어서 보냄)
Server B(수신)측
RTestRepository
public interface RTestRepository extends JpaRepository<RTest, Long> {}
Querydsl사용을 위해 Repository 정의
ReportController
@RestController
@RequestMapping("/report")
@Log4j2
@RequiredArgsConstructor
public class ReportController {
private final RTestRepository rTestRepository;
@Autowired
@PostMapping(value = "/rpost", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> createRTest(@RequestBody RTestDTO rTestDTO) {
// RTestDTO를 RTest Entity에 매핑한다.
RTest rTest = new RTest();
rTest.setName(rTestDTO.getName());
rTest.setMemberId(rTestDTO.getMemberId());
rTest.setGuitar(rTestDTO.getGuitar());
// RTest Entity를 DB에 저장한다.
rTestRepository.save(rTest);
return ResponseEntity.ok("OK");
}
}
@RequestBody로 받아와야 할 형식(DTO)를 정의한다. 받아온 값들을 Entity에 mapping 후 Querydsl이용해서 DB에 저장. String으로 간단하게 OK 반환 원래라면 Service, ServiceImpl을 사용해서 해당 내용들을 분리해야 하나 편의상 축약
위와같이 코드를 구성하고 서버A측에서 만든 Controller를 이용해 post요청을 전송하면
하드코딩된 "name", 10L, "Guitar playing good" 값이 각각 RTestDTO의 name, memberId, guitar에 삽입되어 서버B로 전송된다.
해당 DTO를 전달받은 서버 B는 Querydsl을 이용해 자신의 DB에 전달받은 세 개의 값을 저장하게 된다.
'컴퓨터' 카테고리의 다른 글
[AWS] 스프링부트 배포용 프리티어 EC2서버 만들기 1 (0) | 2023.06.10 |
---|---|
Java InteliJ 프로젝트 생성 시 문제 (0) | 2023.05.15 |
[Ubuntu]Update시 warning띄우는 keyring 관련 문제 해결 (0) | 2023.04.25 |
[WSL] Failed to retrieve available kernel versions. 오류해결 (0) | 2023.04.13 |
[원격데스크톱]공유기를 통한 외부접속을 위해 포트포워딩 하기 (0) | 2022.12.05 |