上一篇我们已经学会了如何创建一个服务提供者,那么这一篇我们来创建一个服务消费者,实现思路是先通过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的一些组件,让他们拥有了不同的身份。服务提供者提供了对外访问的接口,服务消费者也提供了对外访问的接口,只不过接口内部是在调用其他服务的接口,所以从某种意义上讲,服务消费者也是一个服务提供者,其他服务也可以掉用服务消费者的服务。因此,服务之间没有绝对的提供者与消费者,它们之间是可以相互调用的!

Spring Cloud04: RestTemplate的使用的更多相关文章

  1. 对Spring 的RestTemplate进行包装

    Spring的RestTemplate及大地简化了REST Client的开发,但每次还要编写大量的模板代码,代码不够简洁.我对他进行了一次包装,采用接口来声明REST接口,使用Annotation对 ...

  2. Spring’s RestTemplate

    Spring’s RestTemplate /** * After the word document is generated in memory we can upload it to the s ...

  3. 还不知道spring的RestTemplate的妙用吗

    为什么要使用RestTemplate? 随着微服务的广泛使用,在实际的开发中,客户端代码中调用RESTful接口也越来越常见.在系统的遗留代码中,你可能会看见有一些代码是使用HttpURLConnec ...

  4. Spring的RestTemplate

    Spring提供了一个RestTemplate模板工具类,对基于Http的客户端进行了封装,并且实现了对象与json的序列化和反序列化,非常方便.RestTemplate并没有限定Http的客户端类型 ...

  5. Spring中RestTemplate进行Http调用

    Spring中的RestTemplate类源自spring-web,http调用中设置超时时间.设置连接池管理等非常重要,保证了系统的可用性,避免了长时间连接不上或者等待数据返回,拖垮系统. 现贴出工 ...

  6. spring的RestTemplate使用指南

    前言:现在restful接口越来越广泛,而如今很多接口摒弃了传统的配置复杂的webService开发模式,在java领域只需要很简单的springMvc就可以声明为一个控制器,再加上service层, ...

  7. Spring中RestTemplate的使用方法

    一.REST 在互联网中,我们会通过请求url来对网络上的资源做增删改查等动作,这里的请求包含两部分:动词,主要包括增.删.改.查:名词,就是网络中的各种资源.传统的非REST风格的请求方式是把动词和 ...

  8. Spring boot ----RestTemplate学习笔记

    ****spring boot-----restTemplate 封装了HttpURLConnection,HttpClient,Netty等接口访问实现库 restTemplet包含以下部分 Htt ...

  9. 使用Spring的RestTemplate进行接口调用

    引自:http://www.zimug.com/ 1.常见的http服务的通信方式 经常使用的方式有HttpClient.OkHttp.RestTemplate.其中RestTemplate是一种更优 ...

随机推荐

  1. C++ STL 思维导图,脑图,树形图。

    https://blog.csdn.net/weixin_41743247/article/details/90635931

  2. linux当前运行进程

    一:linux查询服务器服务进程 inux中的ps命令是Process Status的缩写.ps命令用来列出系统中当前运行的那些进程.ps命令列出的是当前那些进程的快照, 就是执行ps命令的那个时刻的 ...

  3. 【实用小技巧】spring springmvc集成shiro时报 No bean named 'shiroFilter' available

    查了网上的,很多情况,不同的解决办法,总归一点就是配置文件加载的问题. 先看下配置文件中的配置 web.xml中的主要配置(这是修改后不在报错的:仅仅修改了一个位置:[classpath:spring ...

  4. Pytest自动化测试-简易入门教程(03)

    今天分享内容的重点,和大家来讲一下我们的测试框架--Pytest 讲到这个框架的话呢,可能有伙伴就会问老师,我在学习自动化测试过程中,我们要去学一些什么东西? 第一个肯定要学会的是一门编程语言,比如说 ...

  5. 那些在GitHub能提高你的编程技能的项目

    1.免费的编程书籍 免费的开发手册 167K Repo:github.com/EbookFoundation/free-programming.. 2. 很棒的话题 包含了各种有趣的话题 148k R ...

  6. .Net 中两分钟集成敏感词组件

    现如今大部分服务都会有用户输入,为了服务的正常运行,很多时候不得不针对输入进行敏感词的检测.替换.如果人工做这样的工作,不仅效率低,成本也高.所以,先让代码去处理输入,成为了经济方便的途径.水弟在这里 ...

  7. C++的指针相关概念

    引言 初入c++,肯定会对指针这个概念非常熟悉.但是为什么c/c++要使用指针? 其实每一种编程语言都使用指针,指针并不只是C/C++的独有特性.C++将指针暴露给了用户(程序员),而Java和C#等 ...

  8. StreamReader & StreamWriter

    这节讲StreamReader & StreamWriter,这两个类用于操作字符或者字符串,它将流的操作封装在了底层,相对来说用法比较简单,但是它不支持Seek()方法. 先看一下代码: F ...

  9. Keycloak 13 自定义用户身份认证流程(User Storage SPI)

    Keycloak 版本:13.0.0 介绍 Keycloak 是为现代应用程序和服务提供的一个开源的身份和访问管理的解决方案. Keycloak 在测试环境可以使用内嵌数据库,生产环境需要重新配置数据 ...

  10. Handle详解

    首先通过一个函数启动一个服务器,只提供一个方法并返回Hello World!,当你在浏览器输入http://127.0.0.1:8080,就会看到Hello World. 对于http.ListenA ...