二:RestTemplate

通过RestTemplate可以实现不同微服务之间的调用

RestTemplate是spring框架提供的一种基于RESTful的服务组件,底层对HTTP请求及其相应进行了封装,提供了很多的远程访问REST服务的方式,可以简化代码的开发

如何使用RestTemplate

1.创建maven工程

<?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.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId>
<artifactId>springCloud02</artifactId>
<version>1.0-SNAPSHOT</version> <parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.0.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>

2.创建实体类:

package com.southwind.entity;

import lombok.AllArgsConstructor;
import lombok.Data; @Data
@AllArgsConstructor
public class User {
private Integer id;
private String name;
}

3.持久层

接口:

package com.southwind.repository;

import com.southwind.entity.User;

import java.util.Collection;

public interface UserRepository {
public Collection<User> findAll();
public User findById(Integer id);
public void saveOrUpdate(User user);
public void deleteById(Integer id);
}

实体类:

package com.southwind.repository.impl;

import com.southwind.entity.User;
import com.southwind.repository.UserRepository; import java.util.Collection;
import java.util.HashMap;
import java.util.Map; public class UserRepositoryImpl implements UserRepository {
private static Map<Integer,User> map;
static {
map=new HashMap<>();
map.put(1,new User(1,"张三"));
map.put(2,new User(2,"李四"));
map.put(3,new User(3,"王五")); }
@Override
public Collection<User> findAll() {
return map.values();
} @Override
public User findById(Integer id) {
return map.get(id);
} @Override
public void saveOrUpdate(User user) {
map.put(user.getId(),user);
} @Override
public void deleteById(Integer id) {
map.remove(id);
}
}

测试接口可以使用

RestTemplate访问服务REST服务

1.将RestTemplate的实例化对象通过@Bean注解注入到IoC容器

package com.southwind.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate; @Configuration
public class MyConfig {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
  • 方法名为id名

2.创建RestHandler

package com.southwind.Handler;

import com.southwind.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate; import java.util.Collection; @RestController
@RequestMapping("/rest")
public class RestHandler {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/findall")
public Collection<User> findAll(){
return restTemplate.getForObject("http://localhost:8080/user/findall",Collection.class);
}
@GetMapping("/findbyid/{id}")
public User findById(@PathVariable("id") Integer id){
return restTemplate.getForObject("http://localhost:8080/user/findbyid/{id}",User.class,id);
}
@PostMapping("/save")
public void save(@RequestBody User user){
restTemplate.postForObject("http://localhost:8080/user/save",user,Collection.class);
}
@PutMapping("/update")
public void update(User user){
restTemplate.put("http://localhost:8080/user/save",user);
}
@DeleteMapping("/delete{id}")
public void delete(@PathVariable("id") Integer id){
restTemplate.delete("http://localhost:8080/user/delete{id}",id);
}
}

底层RestTemplate是对http请求和相应的封装,提供了很多访问远程REST服务的方法,基于它的这个特性,我们可以实现不同微服务之间的调用。

服务消费者

1.创建Module,配置环境

<?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.0.xsd">
<parent>
<artifactId>springCloud01</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion> <artifactId>consumer</artifactId> <dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
</project>

2.application.yml

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

3.启动类:

package com.southwind;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class,args);
}
}

4.Handler

package com.southwind.controller;

import com.southwind.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate; import java.util.Collection; @RestController
@RequestMapping("/consumer")
public class StudentHandler {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/findall")
public Collection<Student> findall(){
return restTemplate.getForObject("http://localhost:8010/provider/findall",Collection.class);
}
@GetMapping("/findbyid/{id}")
public Student findById(@PathVariable("id") Integer id){
return restTemplate.getForObject("http://localhost:8010/provider/findbyid/{id}",Student.class,id);
}
@PostMapping("/save")
public void save(@RequestBody Student student){
restTemplate.postForObject("http://localhost:8010/provider/save",student,Collection.class);
}
@DeleteMapping("/delete")
public void deletebyid(Integer id){
restTemplate.delete("http://localhost:8010/provider/delete/{id}",id);
}
}

5.配置类:

package com.southwind.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate; @Configuration
public class MyConfig {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}

RestTemplate的调用方式、服务消费者的更多相关文章

  1. Java微服务(二):服务消费者与提供者搭建

    本文接着上一篇写的<Java微服务(一):dubbo-admin控制台的使用>,上篇文章介绍了docker,zookeeper环境的安装,并参考dubbo官网演示了dubbo-admin控 ...

  2. 7、服务发现&服务消费者Ribbon

    公众号: java乐园 在<服务注册&服务提供者>这一篇可能学习了这么开发一个服务提供者,在生成上服务提供者通常是部署在内网上,即是服务提供者所在的服务器是与互联网完全隔离的.这篇 ...

  3. Dubbo中服务消费者和服务提供者之间的请求和响应过程

    服务提供者初始化完成之后,对外暴露Exporter.服务消费者初始化完成之后,得到的是Proxy代理,方法调用的时候就是调用代理. 服务消费者经过初始化之后,得到的是一个动态代理类,InvokerIn ...

  4. 第二篇:服务消费者(RestTemplate+ribbon)

    第一篇讲了服务的注册,这篇来说说服务的调用,服务与服务的通讯是基于http restful,springcloud的服务调用是通过ribbon方式的,客户端的负载均衡. Talk is cheap.S ...

  5. 玩转SpringCloud(F版本) 二.服务消费者(1)ribbon+restTemplate

    上一篇博客有人问我,Springcloud系列会不会连载 ,大家可以看到我的标签分类里已经开设了SpringCloud专题,所以当然会连载啦,本人最近也是买了本书在学习SpringCloud微服务框架 ...

  6. SpringCloud-创建服务消费者-Ribbon方式(附代码下载)

    场景 SpringCloud-服务注册与实现-Eureka创建服务注册中心(附源码下载): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/deta ...

  7. SpringBoot系列十一:SpringBoot整合Restful架构(使用 RestTemplate 模版实现 Rest 服务调用、Swagger 集成、动态修改日志级别)

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot整合Restful架构 2.背景 Spring 与 Restful 整合才是微架构的核心,虽然在整 ...

  8. SpringCloud-创建服务消费者-Feign方式(附代码下载)

    场景 SpringCloud-服务注册与实现-Eureka创建服务注册中心(附源码下载): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/deta ...

  9. 小D课堂 - 新版本微服务springcloud+Docker教程_4-02 微服务调用方式之ribbon实战 订单调用商品服务

    笔记 2.微服务调用方式之ribbon实战 订单调用商品服务     简介:实战电商项目 订单服务 调用商品服务获取商品信息         1.创建order_service项目         2 ...

  10. 小D课堂 - 新版本微服务springcloud+Docker教程_4-01 常用的服务间调用方式讲解

    笔记 第四章 服务消费者ribbon和feign实战和注册中心高可用 1.常用的服务间调用方式讲解     简介:讲解常用的服务间的调用方式 RPC:             远程过程调用,像调用本地 ...

随机推荐

  1. 机器学习模型评价指标之ROC 曲线、 ROC 的 AUC 和 投资回报率

    前文回顾: 机器学习模型评价指标之混淆矩阵 机器学习模型评价指标之Accuracy.Precision.Recall.F-Score.P-R Curve.AUC.AP 和 mAP 1. 基本指标 1. ...

  2. Web Api出现500 Internal Server Error 错误

    在测试环境一切正常,但是部署到了生产环境发现一直报错.查询网上的方法设置了权限等等.都没有解决 原来发现是数据库连接字符串的问题.只需要把数据库连接字符串修改正确即可!

  3. 【算法总结】【队列均LinkedList】栈和队列、双端队列的使用及案例

    1.栈 初始化:Stack<E> stack = new Stack<>(); 出栈:stack.pop() 或 stack.remove(stack.size() - 1) ...

  4. 【中间件】Docker

    一.Docker (一)基础概念 1.概念 是linux容器的一种封装,它是最流行的Linux容器解决方案,由go语言开发 提供简单易用的容器使用接口,方便创建.使用和销毁 2.应用场景 自动打包.持 ...

  5. OpenAI 推出超神 ChatGPT 注册教程来了

    前几天,OpenAI 推出超神 ChatGPT,非常火爆.但是呢,因为不可抗力原因,大部分人无法体验到.这里我分享一下注册的攻略. 准备 首先能能访问 Google(前置条件,不能明确说,懂得都懂) ...

  6. Qt从实习到搬砖

    Qt C++ 工具箱 从零开始的Qt开发之路 里面大概会写一些和Qt相关的内容,也不说是从0开始,感觉Qt做东西和用 C#也差不了很多?也许吧,总之慢慢来,一步一个脚印,直到给它拿下. 2022.5. ...

  7. 【深入浅出SpringCloud原理及实战】「SpringCloud-Alibaba系列」微服务模式搭建系统基础架构实战指南及版本规划踩坑分析

    Spring Cloud Alibaba Nacos Discovery Spring Boot 应用程序在服务注册与发现方面提供和 Nacos 的无缝集成. 通过一些简单的注解,您可以快速来注册一个 ...

  8. 高性能 Jsonpath 框架,Snack3 3.2.50 发布

    Snack3,一个高性能的 JsonPath 框架 借鉴了 Javascript 所有变量由 var 申明,及 Xml dom 一切都是 Node 的设计.其下一切数据都以ONode表示,ONode也 ...

  9. 如何在SpringBoot中优雅地重试调用第三方API?

    前言 作为后端程序员,我们的日常工作就是调用一些第三方服务,将数据存入数据库,返回信息给前端.但你不能保证所有的事情一直都很顺利.像有些第三方API,偶尔会出现超时.此时,我们要重试几次,这取决于你的 ...

  10. 自研ORM框架 实现类似EF Core Include 拆分查询 支持自定义条件、排序、选择

    Baozi, I'm Mr.Zhong I like to brush TikTok, I know that anchors like to call it that, haha!Recently, ...