728x90
다른 spring boot 프로그램과 내 프로그램끼리 api를 사용하고 싶었는데
webclient가 제일 편하다고 해서 사용했다. 다른 것도 많은데 이게 제일 코드가 적고 간편한 것 같다.
gradle
implementation("org.springframework.boot:spring-boot-starter-webflux")
webclient.post() - parameter
import jakarta.annotation.PostConstruct;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.DefaultUriBuilderFactory;
import static org.springframework.web.util.DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY;
@Service
public class WebClientService {
@Value("${webclient.url:http://상대주소/api/test}")
private String url;
private WebClient webClient;
@PostConstruct
public void webClient(){
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(url);
factory.setEncodingMode(VALUES_ONLY);
webClient = WebClient.builder()
.uriBuilderFactory(factory)
.baseUrl(url)
.build();
}
public void postWebClient(String message){
try {
// 여기서 queryParam으로 parameter값을 넣어 post api를 사용할 수 있다.
// 간단하게 생각하자면 queryParam이 @RequestParam 자리??
// body() 로 값을 넣어서 보낼 수 있다.
.uri(url -> url
.queryParam("message", message)
.build())
.retrieve()
.bodyToMono(String.class)
.block();
}catch(Exception e){}
}
}
나중에 쓸일이 생기면 써야겠다..
장단점이 있으니
728x90
반응형