RestTemplate adalah klien yang disediakan oleh Spring untuk mengakses layanan REST. RestTemplate menyediakan berbagai cara yang nyaman untuk mengakses layanan HTTP jarak jauh, yang dapat sangat meningkatkan efisiensi penulisan klien. Di blog sebelumnya, //www.vevb.com/article/132885.htm, klien Jersey telah digunakan untuk mengimplementasikan layanan RESTful yang mengkonsumsi boot musim semi. Selanjutnya, kami menggunakan RestTemplate untuk mengkonsumsi layanan RESTful dalam contoh sebelumnya. Contoh sebelumnya:
Springboot mengintegrasikan database memori H2 untuk mencapai tes unit dan ketidakrelevanan database
Layanan Restful yang disediakan oleh contoh ini adalah sebagai berikut: http: // localhost: 7900/user/1
{"id": 1, "nama pengguna": "user1", "name": "Zhang San", "Age": 20, "Balance": 100.00}
Ketergantungan file pom adalah sebagai berikut:
<? 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 xsi: schemalocation = "http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <ModelVersion> 4.0.0 </ModelVersion> <groupid> com.chhlri <ArTifactId> Springboot-Rest-template </stifactid> <version> 0.0.1-Snapshot </version> <packaging> Jar </packaging> <name> Springboot-Rest-template </name> <creckripe> Proyek Demo untuk Spring Boot RestTemplate </description> <parent> <groupid> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <Project.Reporting.OutputEncoding> UTF-8 </project.reporting.outputEncoding> <Java.Version> 1.7 </java.version> </Properties> </Dependencies> <Ruppendency> <GroupDid org.springframework.BOOT </groupid> <Artifactid> <dependency> <GroupId> org.springframework.boot </groupid> <ArTifactId> spring-boot-starter-test </t Artifactid> <scope> test </opope> </dependency> <!-Paket Hot Deployment, untuk debugging convenience, tambahkan paket ini-> <groupping> <groupding> Paket Debugging. <ArTifactId> Spring-Boot-DevTools </stifactId> <pilihan> true </opsional> </dependency> </dependencies> <build> <dlugin> <lugin> <lugin> <clugin> <groupid> org.springframework.boot </groupId <artifactid> <artifactid> <artifactid> <artifactid> <artifactid> <artifactid> <artifactid> <artifactid> <artifactid> <artifactid> <artifactid> <artifactid> <crupin> <croupin> <crupin> <crupin> </jadi Project>
Karena kita perlu mengonversi string JSON yang sesuai menjadi objek pengguna setelah kita menggunakan RestTemplate untuk memanggil layanan RESTful, kita perlu menyalin kelas ini ke proyek, sebagai berikut:
paket com.chhliu.springboot.restful.vo; impor java.math.bigdecimal; pengguna kelas publik {private long ID; nama pengguna string pribadi; nama string pribadi; usia pendek pribadi; keseimbangan privat besar; // ... oloskan metode pengambil dan setter/ ** * Perhatian: * Detail: TODO * @Author chhliu * Waktu penciptaan: 2017-1-20 2:05:45 PM * @return */ @override Public String ToString () {return "User [id =" + id + ", nama pengguna =" + nama pengguna + "," ID = " + ID +", nama pengguna = " +" + "," ID = " + ID +", nama pengguna = " +" + ", nama USERRING =", "ID =" + " +" + " "]"; }} paket com.chhliu.springboot.restful.controller; impor org.springframework.beans.factory.annotation.Autowired; impor org.springframework.web.bind.annotation.getmapping; impor org.springframework.web.bind.annotation.pathvariable; impor org.springframework.web.bind.annotation.RestController; impor org.springframework.web.client.resttemplate; impor com.chhliu.springboot.restful.vo.user; @RestController kelas publik restTemplateController {@autowired private restTemplate restTemplate; @GetMapping ("/template/{id}") pengguna publik findbyid (@pathvariable id long id) {// http: // localhost: 7900/user/adalah url yang sesuai dari pengguna layanan sebelumnya u = this.restemplate.getForObject ("http: // localhost u = this.restemplate. System.out.println (u); mengembalikanmu; }} paket com.chhliu.springboot.restful; impor org.springframework.beans.factory.annotation.Autowired; impor org.springframework.boot.springapplication; impor org.springframework.boot.autoconfigure.springbootApplication; impor org.springframework.boot.web.client.resttemplateBuilder; impor org.springframework.context.annotation.bean; impor org.springframework.web.client.resttemplate; @SpringbootApplication kelas publik springbootresttemplateApplication {// hati -hati saat memulai karena kita menyuntikkan resttemplate ke pengontrol, kita perlu instantiate instance dari kelas saat memulai @Autowired private resttemplateBuilder Builder; // Gunakan RestTemplateBuilder untuk membuat instantiate objek RestTemplate. Spring telah menyuntikkan instance RestTemplate secara default @Bean Public Resttemplate restTemplate () {return builder.build (); } public static void main (string [] args) {springApplication.run (springbootresttemplateApplication.class, args); }} Masukkan: http: // localhost: 7902/template/1 di browser Anda
Hasil tes adalah sebagai berikut:
Hasil Pencetakan Konsol:
Pengguna [id = 1, nama pengguna = user1, name = zhang san, usia = 20, saldo = 100.00]
Melalui tes di atas, ditunjukkan bahwa kami telah berhasil menyebut layanan Restful Spring Boot.
Ada hal yang sangat buruk dalam tes di atas.
Pengguna u = this.resttemplate.getForObject ("http: // localhost: 7900/user/" + id, user.class); Kode keras muncul di sini. Ketika alamat server berubah, kode yang sesuai perlu diubah, dan metode yang ditingkatkan diperlukan untuk menulis alamat layanan yang tenang ke dalam file konfigurasi.
Ubah pengontrol sebagai berikut:
paket com.chhliu.springboot.restful.controller; impor org.springframework.beans.factory.annotation.Autowired; impor org.springframework.beans.factory.annotation.value; impor org.springframework.web.bind.annotation.getmapping; impor org.springframework.web.bind.annotation.pathvariable; impor org.springframework.web.bind.annotation.RestController; impor org.springframework.web.client.resttemplate; impor com.chhliu.springboot.restful.vo.user; @RestController kelas publik restTemplateController {@autowired private restTemplate restTemplate; // Alamat URL yang sesuai dengan layanan RESTful @Value ("$ {user.userservicePath}") Private String UserServicePath; @GetMapping ("/template/{id}") pengguna publik findById (@pathvariable long id) {user u = this.resttemplate.getForObject (this.userservicePath + id, user.class); System.out.println (u); mengembalikanmu; }}File konfigurasi dimodifikasi sebagai berikut:
server.port: 7902 user.userservicePath = http: // localhost: 7900/user/
Mulai program:
Saya menemukan bahwa tesnya OK. Nanti, kami akan memperkenalkan Spring Cloud untuk lebih meningkatkan metode panggilan ini!
Di atas adalah semua konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.