Spring Cloud(四):RestTemplate的使用

个人博客导航页(点击右侧链接即可打开个人博客):大牛带你入门技术栈 

我们已经学会了如何创建一个服务提供者,那么这一篇我们来创建一个服务消费者,实现思路是先通过Spring boot搭建一个微服务应用,再通过Eureka Client把它注册到注册中心Eureka Server,成为一个服务消费者。那么服务消费者如何调用服务提供者的接口呢,那么我们首先要来介绍一个组件RestTemplate的使用。

一、什么是RestTemplate

     RestTemplate 是 Spring 框架提供的基于 REST 的服务组件,底层是对 HTTP 请求及响应进⾏了封装, 提供了很多访问 RETS 服务的⽅法,可以简化代码开发。

二、如何使用RestTemplate

    1.创建一个maven工程作为子服务

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    <version>2.0.2.RELEASE</version>
</dependency>

    2.创建application.yml,代码如下

server:
  port: 8080
spring:
  application:
    name: consumer
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true

    2.创建与服务提供者相同的实体类,代码如下

package com.frr.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data //生成Getter,Setter,equals,canEqual,hasCode,toString等方法
@AllArgsConstructor //添加一个构造函数,该构造函数含有所有已声明字段属性参数
@NoArgsConstructor //创建一个无参构造函数
public class Student {
	private long id;
	private String name;
	private int age;
}

    3.创建controller,并且在方法中调用服务提供者的接口,代码如下

package com.frr.controller;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.frr.entity.Student;

@RestController
@RequestMapping("/consumer")
public class RestTemplateController {
	
	@Autowired
	private RestTemplate restTemplate;
	
	@GetMapping("/findAll")
	@SuppressWarnings("unchecked")
	public Collection<Student> findAll(){
		return restTemplate.getForEntity("http://localhost:8010/student/findAll", Collection.class).getBody();
	}
	
	@SuppressWarnings("unchecked")
	@GetMapping("/findAll2")
	public Collection<Student> findAll2(){
		return restTemplate.getForObject("http://localhost:8010/student/findAll",Collection.class);
	}
	
	@GetMapping("/findById/{id}")
	public Student findById(@PathVariable("id") long id){
		return	restTemplate.getForEntity("http://localhost:8010/student/findById/{id}",Student.class,id).getBody();
	}
	
	@GetMapping("/findById2/{id}")
	public Student findById2(@PathVariable("id") long id){
		return	restTemplate.getForObject("http://localhost:8010/student/findById/{id}",Student.class,id);
	}
	
	@PostMapping("/save")
	public void save(@RequestBody Student student){
		restTemplate.postForEntity("http://localhost:8010/student/save",student,null).getBody();
	}
	
	@PostMapping("/save2")
	public void save2(@RequestBody Student student){
		restTemplate.postForObject("http://localhost:8010/student/save",student,null);
	}
		
	@PutMapping("/update")
	public void update(@RequestBody Student student){
		restTemplate.put("http://localhost:8010/student/update",student);
	}
	
	@DeleteMapping("/deleteById/{id}")
	public void deleteById(@PathVariable("id") long id){
		restTemplate.delete("http://localhost:8010/student/deleteById/{id}",id);
	}
	
}

    4.创建启动类,需要注意的是,需要在启动类里将RestTemplate的实例进行注入的,这里采用@Bean的方式,代码如下

package com.frr;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class RestTemplateApplication {
	public static void main(String[] args) throws Exception {
		SpringApplication.run(RestTemplateApplication.class, args);
	}
	
	@Bean
	public RestTemplate restTemplate(){
		return new RestTemplate();
	}
}

5.依次启动注册中心、服务提供者、服务消费者,利用Postman工具测试,不同的请求可获得相同的数据返回

    * 8010服务提供者findAll接口返回数据如下

    * 8080服务消费者findAll接口返回数据如下

    *结论:数据返回一致,服务消费者成功调用服务提供者的接口!

6.总结

    服务提供者和服务消费者从代码的层面来看,是没有太大区别的,他们本身都是Spring boot的工程,我们在此基础上,通过Spring Cloud的一些组件,让他们拥有了不同的身份。服务提供者提供了对外访问的接口,服务消费者也提供了对外访问的接口,只不过接口内部是在调用其他服务的接口,所以从某种意义上讲,服务消费者也是一个服务提供者,其他服务也可以掉用服务消费者的服务。因此,服务之间没有绝对的提供者与消费者,它们之间是可以相互调用的!

附Java/C/C++/机器学习/算法与数据结构/前端/安卓/Python/程序员必读/书籍书单大全:

(点击右侧 即可打开个人博客内有干货):技术干货小栈
=====>>①【Java大牛带你入门到进阶之路】<<====
=====>>②【算法数据结构+acm大牛带你入门到进阶之路】<<===
=====>>③【数据库大牛带你入门到进阶之路】<<=====
=====>>④【Web前端大牛带你入门到进阶之路】<<====
=====>>⑤【机器学习和python大牛带你入门到进阶之路】<<====
=====>>⑥【架构师大牛带你入门到进阶之路】<<=====
=====>>⑦【C++大牛带你入门到进阶之路】<<====
=====>>⑧【ios大牛带你入门到进阶之路】<<====
=====>>⑨【Web安全大牛带你入门到进阶之路】<<=====
=====>>⑩【Linux和操作系统大牛带你入门到进阶之路】<<=====

天下没有不劳而获的果实,望各位年轻的朋友,想学技术的朋友,在决心扎入技术道路的路上披荆斩棘,把书弄懂了,再去敲代码,把原理弄懂了,再去实践,将会带给你的人生,你的工作,你的未来一个美梦。

发布了110 篇原创文章 · 获赞 0 · 访问量 3718

猜你喜欢

转载自blog.csdn.net/jishulaozhuanjia/article/details/104835860