SpringCloud RestTemplate服务间调用

Posted 一万年太久只争朝夕

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringCloud RestTemplate服务间调用相关的知识,希望对你有一定的参考价值。

SpringCloud Rest学习环境搭建:服务提供者

介绍

  • 我们会使用一个Dept部门模块做一个微服务通用案例Consumer消费者(Client)通过REST调用Provider提供者(Server)提供的服务。
  • 回顾Spring,SpringMVC,Mybatis等以往学习的知识。
  • Maven的分包分模块架构复习。
一个简单的Maven模块结构是这样的:
-- app-parent: 一个父项目(app-parent)聚合了很多子项目(app-util\\app-dao\\app-web...)
  |-- pom.xml
  |
  |-- app-core
  ||---- pom.xml
  |
  |-- app-web
  ||---- pom.xml
  ......

一个父工程带着多个Moudule子模块

MicroServiceCloud父工程(Project)下初次带着3个子模块(Module)

  • microservicecloud-api 【封装的整体entity/接口/公共配置等】
  • microservicecloud-consumer-dept-80 【服务提供者】
  • microservicecloud-provider-dept-8001 【服务消费者】

SpringCloud版本选择

大版本说明

SpringBoot SpringCloud 关系
1.2.x Angel版本(天使) 兼容SpringBoot1.2x
1.3.x Brixton版本(布里克斯顿) 兼容SpringBoot1.3x,也兼容SpringBoot1.4x
1.4.x Camden版本(卡姆登) 兼容SpringBoot1.4x,也兼容SpringBoot1.5x
1.5.x Dalston版本(多尔斯顿) 兼容SpringBoot1.5x,不兼容SpringBoot2.0x
1.5.x Edgware版本(埃奇韦尔) 兼容SpringBoot1.5x,不兼容SpringBoot2.0x
2.0.x Finchley版本(芬奇利) 兼容SpringBoot2.0x,不兼容SpringBoot1.5x
2.1.x Greenwich版本(格林威治)

实际开发版本关系

spring-boot-starter-parent spring-cloud-dependencles
版本号 发布日期 版本号 发布日期
1.5.2.RELEASE 2017-03 Dalston.RC1 2017-x
1.5.9.RELEASE 2017-11 Edgware.RELEASE 2017-11
1.5.16.RELEASE 2018-04 Edgware.SR5 2018-10
1.5.20.RELEASE 2018-09 Edgware.SR5 2018-10
2.0.2.RELEASE 2018-05 Fomchiey.BULD-SNAPSHOT 2018-x
2.0.6.RELEASE 2018-10 Fomchiey-SR2 2018-10
2.1.4.RELEASE 2019-04 Greenwich.SR1 2019-03

使用后两个

创建父工程

  • 新建父工程项目springcloud,切记Packageing是pom模式
  • 主要是定义POM文件,将后续各个子模块公用的jar包等统一提取出来,类似一个抽象父类

image-20210811215453501

pom.xml

<?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>com.haust</groupId>
    <artifactId>springcloud</artifactId>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>springcloud-api</module>
        <module>springcloud-provider-dept-8001</module>
        <module>springcloud-consumer-dept-80</module>
        <module>springcloud-eureka-7001</module>
        <module>springcloud-eureka-7002</module>
        <module>springcloud-eureka-7003</module>
        <module>springcloud-provider-dept-8002</module>
        <module>springcloud-provider-dept-8003</module>
        <module>springcloud-consumer-dept-feign</module>
        <module>springcloud-provider-dept-hystrix-8001</module>
        <module>springcloud-consumer-hystrix-dashboard</module>
        <module>springcloud-zuul-9527</module>
        <module>springcloud-config-server-3344</module>
        <module>springcloud-config-client-3355</module>
        <module>springcloud-config-eureka-7001</module>
        <module>springcloud-config-dept-8001</module>
    </modules>
    <!--打包方式  pom-->
    <packaging>pom</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <junit.version>4.12</junit.version>
        <log4j.version>1.2.17</log4j.version>
        <lombok.version>1.16.18</lombok.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>0.2.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--springCloud的依赖-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--SpringBoot-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.1.4.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--数据库-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.10</version>
            </dependency>
            <!--SpringBoot 启动器-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.2</version>
            </dependency>
            <!--日志测试~-->
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-core</artifactId>
                <version>1.2.3</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

springcloud-api子模块

创建springcloud-api工程,也是一个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">
    <parent>
        <artifactId>springcloud</artifactId>
        <groupId>com.kuang</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud-api</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <!--当前的moudle自己需要的依赖,如果父依赖中已经配置了版本,这里就不用写了-->
    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

</project>

创建db01数据库

创建一个db01数据库,并创建一张dept部门表:

create table dept
(
    deptno    bigint auto_increment
        primary key,
    dname     varchar(60) null,
    db_source varchar(60) null
)
    comment \'部门表\';
insert into dept (dname,db_source) values (\'开发部\',database());
insert into dept (dname,db_source) values (\'人事部\',database());
insert into dept (dname,db_source) values (\'财务部\',database());
insert into dept (dname,db_source) values (\'市场部\',database());
insert into dept (dname,db_source) values (\'运维部\',database());

创建实体类

package com.kuang.springcloud.pojo;

import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;

@Data
@NoArgsConstructor
@Accessors(chain=true) //链式写法 @Builder注解也可以
public class Dept implements Serializable { //实体类,

    private Long deptno;
    private String dname;

    //这个数据存在哪个数据库的字段  微服务:是可以一个服务对应一个数据库的,
    // 同一个信息可能存储在不同的数据库
    private String db_source;

    public Dept(String dname) {
        this.dname = dname;
    }
}

springcloud-api子模块只需要一个实体类就够了

springcloud-provider-dept-8001提供者模块

导入相关依赖

<?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>springcloud</artifactId>
        <groupId>com.kuang</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud-provider-dept-8001</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!--我们需要拿到实体类,所以要配置api module-->
        <dependency>
            <groupId>com.kuang</groupId>
            <artifactId>springcloud-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <!--springboot test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--jetty-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>
        <!--热部署工具-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>

</project>

增加配置,编写服务

由于新建的一个maven模块,需要在resources目录下新建application.yml:

server:
  port: 8001

#mybatis配置
mybatis:
  type-aliases-package: com.kuang.springcloud.pojo
  mapper-locations: classpath:mybatis/mapper/*.xml
  config-location: classpath:mybatis/mybatis-config.xml


#springboot的配置

spring:
  application:
    name: springcloud-provider-dept
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource #数据源
    driver-class-name: org.gjt.mm.mysql.Driver
    url: jdbc:mysql://localhost:3306/db01?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    username: root
    password: 123456

再新建mapper目录以及mybatis核心配置文件mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
    <settings>
        <!--开启二级缓存-->
        <setting name="cacheEnabled" value="true"/>
    </settings>

</configuration>

image-20210812031556184

编写controller,service,dao以及mapper.xml文件,还有主启动类,详情见后面贴出来的git代码地址

image-20210812173232489

SpringCloud Rest学习环境搭建:服务消费者

导入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.0.xsd">
    <parent>
        <artifactId>springcloud</artifactId>
        <groupId>com.kuang</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springcloud-consumer-dept-80</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <!--实体类+web-->
    <dependencies>
        <dependency>
            <groupId>com.kuang</groupId>
            <artifactId>springcloud-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>
</project>

编写application.yml配置文件

由于只配置了个端口,所以忽略详情见码云代码!

注入RestTemplate

由于消费者需要调用服务提供者的接口,这里我们采取RestTemplate的方式,而RestTemplate没有注入到spring容器中,我们首先注入进去

package com.kuang.springcloud.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ConfigBean {

    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

}

调用提供者接口

然后用如下编写消费者服务去掉提供者提供的接口:

@RestController
public class DeptConsumerController {

    //RestTemplate ..供我们直接调用就可以

    @Autowired
    private RestTemplate restTemplate; //提供多种便捷访问远程http服务的方法,它是一种简单的访问restful风格服务的模板

    private static final String REST_URL_PREFIX = "http://localhost:8001/";

    @RequestMapping("/consumer/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id){
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id,Dept.class);
    }

    @RequestMapping("/consumer/dept/add")
    public boolean add(Dept dept){
        return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add",dept,Boolean.class);
    }

    @RequestMapping("/consumer/dept/list")
    public List<Dept> list(){
        return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list",List.class);
    }

}

测试

最后测试完美调用!

代码在spingcloud项目的springcoud-api和springcloud-provider-dept-8001模块,后面会给出码云地址!

以上是关于SpringCloud RestTemplate服务间调用的主要内容,如果未能解决你的问题,请参考以下文章

SpringCloud---基于RestTemplate微服务项目案例

微服务架构整理-(七SpringCloud实战之RestTemplate)

微服务架构整理-(七SpringCloud实战之RestTemplate)

精通springcloud:将RestTemplate与服务发现结合使用

SpringCloud RestTemplate服务间调用

SpringCloud http客户端Feign -- Feign替代RestTemplate