RestTemPlate은 Spring이 REST 서비스에 액세스하기 위해 제공하는 클라이언트입니다. RestTemplate은 원격 HTTP 서비스에 액세스하는 다양한 편리한 방법을 제공하여 고객의 쓰기 효율성을 크게 향상시킬 수 있습니다. 이전 블로그 인 //www.vevb.com/article/132885.htm에서 Jersey Client는 Spring Boot를 소비하는 나머지 서비스를 구현하는 데 사용되었습니다. 다음으로, 우리는 RestTemplate을 사용하여 이전 예제에서 RESTFUL 서비스를 소비합니다. 이전 예 :
SpringBoot는 H2 메모리 데이터베이스를 통합하여 단위 테스트 및 데이터베이스 관련성을 달성합니다.
이 예에서 제공되는 편안한 서비스는 다음과 같습니다. http : // localhost : 7900/user/1
{ "id": 1, "username": "user1", "name": "Zhang San", "Age": 20, "Balance": 100.00}
POM 파일 종속성은 다음과 같습니다.
<? xml version = "1.0"encoding = "utf-8"?> <project xmlns = "http://maven.apache.org/pom/4.0.0"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance" xsi : schemalocation = "http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.xsd"> <modeversion> 4.0.0 </modelversion> <groupid> com.chhhliu.springboot.restful </groupid> <Artifactid> SpringBoot-Rest-Template </artifactid> <버전> 0.0.1-snapshot </version> <packaging> jar </packaging> <name> springboot-rest-template </name> <description> 스프링 부팅 레드 플레이트의 데모 프로젝트 </descript> <cerid> org.springframework.boot.boot.boot. <아티 팩트> 스프링 부트 스타터-팔렌트 </artifactid> <bersion> 1.4.3.3.3.3.3.3.3.3.3.3.3.3.30 </version </version </version </version> <realativePath/> <!-리포지토리에서 부모를 조회합니다-> </parent> <properties> <project.build.SourceOding> UTF-8 </project.build.sourceencoding> <project.reporting.outputencoding> utf-8 </project.reporting.outputencoding> <java.version> 1.7 </java.version> </properties> <pectionals> <guplendency> <groupid> org.springframwork.boot </groupid> <artifactid> spring-we-starter-starterb> <pectionency> <groupid> org.springframework.boot </groupid> <artifactid> 스프링 부트 스타터-테스트 </artifactid> <artifactid> <scope> test </scope> </fectionency> <!-핫 배포, 핫 배포 종속성 패키지, 디버깅 편의성, <prection> <groupd> org.spramframframwerk.spramewwork.spramed> <Artifactid> spring-boot-devtools </artifactid> <pectional> true </septional> </fectionement> </fectionements> <build> <plugins> <flugin> <flugin> <groupid> org.springframework.boot </groupid> </flugin> </flugin> </artifactid> </project>
RestTemplate를 사용하여 RESTFul 서비스를 호출 한 후 해당 JSON 문자열을 사용자 객체로 변환해야하므로 다음과 같이이 클래스를 프로젝트에 복사해야합니다.
패키지 com.chhliu.springboot.restful.vo; import java.math.bigdecimal; 공개 클래스 사용자 {private long id; 개인 문자열 사용자 이름; 개인 문자열 이름; 개인 단기 연령; 개인 대형 균형; // ... getter and setter methods/ ** *주의 : * 세부 사항 : todo * @author chhliu * 생성 시간 : 2017-1-20 PM * @return */ @override public string toString () {retud "user [id =" + id + ", username =" + username + ", name =" + name + ", name +" "]"; }} 패키지 com.chhliu.springboot.restful.controller; org.springframework.beans.factory.annotation.autowired; org.springframework.web.bind.annotation.getMapping; import org.springframework.web.bind.annotation.pathvariable; org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.resttemplate; import com.chhliu.springboot.restful.vo.user; @RestController Public Class RestTemPlateController {@autowired private resttemplate resttemplate; @GetMapping ( "/template/{id}") public user findByid (@pathvariable long id) {// http : // localhost : 7900/user/이전 서비스의 해당 URL입니다. System.out.println (u); u; }} 패키지 com.chhliu.springboot.restful; org.springframework.beans.factory.annotation.autowired; org.springframework.boot.springApplication import; org.springframework.boot.autoconfigure.springbootapplication import; org.springframework.boot.web.client.resttemplatebuilder; import org.springframework.context.annotation.bean; import org.springframework.web.client.resttemplate; @SpringBootApplication public class springbootresttemplateApplication {// resttemplate를 컨트롤러에 주입하기 때문에 시작할 때주의해야합니다. @autowired private resttemplatebuilder builder를 시작할 때 클래스의 인스턴스를 인스턴스화해야합니다. // resttemplatebuilder를 사용하여 resttemplate 객체를 인스턴스화합니다. 스프링은 기본적으로 resttemplate 인스턴스를 주입했습니다 @bean public resttemplate resttemplate () {return builder.build (); } public static void main (string [] args) {springApplication.run (springbootrestTemplateApplication.class, args); }} 브라우저에서 http : // localhost : 7902/template/1을 입력하십시오
테스트 결과는 다음과 같습니다.
콘솔 인쇄 결과 :
user [id = 1, username = user1, name = zhang san, age = 20, balance = 100.00]
위의 테스트를 통해 Spring Boot Restful Service를 성공적으로 호출 한 것으로 나타났습니다.
위의 테스트에는 매우 나쁜 것이 있습니다.
user u = this.resttemplate.getForObject ( "http : // localhost : 7900/user/" + id, user.class);
하드 코드가 여기에 나타납니다. 서버 주소가 변경되면 해당 코드를 변경해야하며 나머지 서비스의 주소를 구성 파일에 작성하려면 개선 된 메소드가 필요합니다.
다음과 같이 컨트롤러를 수정하십시오.
패키지 com.chhliu.springboot.restful.controller; org.springframework.beans.factory.annotation.autowired; org.springframework.beans.factory.annotation.value import; org.springframework.web.bind.annotation.getMapping; import org.springframework.web.bind.annotation.pathvariable; org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.resttemplate; import com.chhliu.springboot.restful.vo.user; @RestController Public Class RestTemPlateController {@autowired private resttemplate resttemplate; // restful service @Value에 해당하는 URL 주소 ( "$ {user.userServicePath}") private String usererVicePath; @GetMapping ( "/템플릿/{id}") public user findById (@PathVariable long id) {user u = this.resttemplate.getForObject (this.UserServicePath + id, user.class); System.out.println (u); u; }}구성 파일은 다음과 같이 수정됩니다.
Server.port : 7902 user.userservicepath = http : // localhost : 7900/user/
프로그램 시작 :
시험이 괜찮다는 것을 알았습니다. 나중에, 우리는이 호출 방법을 더욱 향상시키기 위해 Spring Cloud를 도입 할 것입니다!
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.