基于RestTemplate微服务项目

核能气质少年 提交于 2019-12-07 16:20:29

在写SpringCloud搭建微服务之前,我想先搭建一个不通过springcloud只通过SpringBoot和Mybatis进行模块之间额通讯。然后在此基础上再添加SpringCloud框架。

下面先对案例做个说明

      该项目有一个maven父模块,其中里面有三个子模块:

                                   serverspringcloud:整体父工程。

                            serverspringcloud-api:公共子模块,放公共实体对象。

 serverspringcloud-provider-dept-8001:部门微服务提供者。

  serverspringcloud-consumer-dept-80:部门微服务消费者。调用部分微服务提供者接口进行CRUD操作。

 

一、构建父工程

主要步骤:

   (1) 创建一个Maven父工程并命名serverspringcloud

   (2)  打包方式为POM

   (3) 在pom.xml中定义各依赖的版本号(若Module中pom.xml的依赖没有指定版本号,则会根据父工程的版本号加入依赖)

1、 创建一个Maven父工程

2、 打包方式为POM

 

3、 在pom.xml中定义各依赖的版本号

<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.jincou.springcloudrest</groupId>
<artifactId>serverspringcloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<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.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.9.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.31</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</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>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<finalName>serverspringcloud</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<delimiters>
<delimit>$</delimit>
</delimiters>
</configuration>
</plugin>
</plugins>
</build>


<!-- 说明下当你刚开始创建父工程的时候是没有下面这些信息的,当你在父工程下每新建一个子模块那么在这里都会添加一个子模块的信息-->
<modules>
<module>serverspringcloud-api</module>
<module>serverspringcloud-provider-dept-8001</module>
<module>serverspringcloud-consumer-dept-80</module>
</modules>
</project>

pom.xml

复制代码
<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.jincou.springcloudrest</groupId>
  <artifactId>serverspringcloud</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <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.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>1.5.9.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.0.4</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.0.31</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.0</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>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <finalName>serverspringcloud</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <delimiters>
                        <delimit>$</delimit>
                    </delimiters>
                </configuration>
            </plugin>
        </plugins>
    </build>


<!-- 说明下当你刚开始创建父工程的时候是没有下面这些信息的,当你在父工程下每新建一个子模块那么在这里都会添加一个子模块的信息-->
    <modules>
        <module>serverspringcloud-api</module>
        <module>serverspringcloud-provider-dept-8001</module>
        <module>serverspringcloud-consumer-dept-80</module>
    </modules>
</project>
复制代码

 

二、构建serverspringcloud-api(公共子模块)

 主要步骤

      (1) 在父工程下新建Maven的Module,打包方式为jar

      (2) 在该Module下pom.xml中加入其它需要的依赖

      (3) 完成后先clean一下Maven项目,然后再install提供给其它模块调用 

 1、在父工程下新建Maven的Module,打包方式为jar

 

在创建完子模块后看下pom.xml的Overview视图的一些信息。

 

 2、 在该Module下pom.xml中加入其它需要的依赖

<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>
<parent>
<groupId>com.jincou.springcloudrest</groupId>
<artifactId>serverspringcloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<!-- 我在创建时没有重新指明groupId那就默认用父类的groupId -->
<artifactId>serverspringcloud-api</artifactId>
<!-- 该子模块下目前我并没有添加新的jar -->
</project>

pom.xml

复制代码
<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>
  <parent>
    <groupId>com.jincou.springcloudrest</groupId>
    <artifactId>serverspringcloud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <!-- 我在创建时没有重新指明groupId那就默认用父类的groupId -->
  <artifactId>serverspringcloud-api</artifactId>
   <!-- 该子模块下目前我并没有添加新的jar -->
</project>
复制代码

 3、我在这里面添加了一个Dept实体

 

Dept实体

package com.jincou.springcloud.entities;

import java.io.Serializable;


public class Dept implements Serializable
{
private Long deptno; // 主键
private String dname; // 部门名称
private String db_source;// 来自那个数据库,因为微服务架构可以一个服务对应一个数据库,同一个信息被存储到不同数据库

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

public Dept(Long deptno, String dname, String db_source) {
super();
this.deptno = deptno;
this.dname = dname;
this.db_source = db_source;
}

public Dept() {
super();
}

public Long getDeptno() {
return deptno;
}

public void setDeptno(Long deptno) {
this.deptno = deptno;
}

public String getDname() {
return dname;
}

public void setDname(String dname) {
this.dname = dname;
}

public String getDb_source() {
return db_source;
}

public void setDb_source(String db_source) {
this.db_source = db_source;
}


}

Dept类

复制代码
package com.jincou.springcloud.entities;

import java.io.Serializable;


public class Dept implements Serializable
{
    private Long     deptno; // 主键
    private String     dname; // 部门名称
    private String     db_source;// 来自那个数据库,因为微服务架构可以一个服务对应一个数据库,同一个信息被存储到不同数据库
    
    public Dept(String dname)
    {
        super();
        this.dname = dname;
    }

    public Dept(Long deptno, String dname, String db_source) {
        super();
        this.deptno = deptno;
        this.dname = dname;
        this.db_source = db_source;
    }

    public Dept() {
        super();
    }

    public Long getDeptno() {
        return deptno;
    }

    public void setDeptno(Long deptno) {
        this.deptno = deptno;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getDb_source() {
        return db_source;
    }

    public void setDb_source(String db_source) {
        this.db_source = db_source;
    }
    
    
}
复制代码

 

 三、创建部门微服务提供者

  步骤:这个就比较复杂了,具体看下面的图

下面就展示几个比较重要的环节

 1、pom.xml文件

   (1)先看下pom.xml的Overview视图的一些信息。

 

 (2)pom.xml

<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>
<parent>
<groupId>com.jincou.springcloudrest</groupId>
<artifactId>serverspringcloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>serverspringcloud-provider-dept-8001</artifactId>


<dependencies>
<!-- 引入自己定义的api通用包,可以使用Dept部门Entity -->
<dependency>
<groupId>com.jincou.springcloudrest</groupId>
<artifactId>serverspringcloud-api</artifactId>
<version>${project.version}</version>
</dependency>

<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- 修改后立即生效,热部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>

</project>

pom.xml

复制代码
<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>
  <parent>
    <groupId>com.jincou.springcloudrest</groupId>
    <artifactId>serverspringcloud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>serverspringcloud-provider-dept-8001</artifactId>
  
  
  <dependencies>
        <!-- 引入自己定义的api通用包,可以使用Dept部门Entity -->
        <dependency>
         <groupId>com.jincou.springcloudrest</groupId>
            <artifactId>serverspringcloud-api</artifactId>
            <version>${project.version}</version>
        </dependency>
    
        <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!-- 修改后立即生效,热部署 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>
    
</project>
复制代码

2、application.yml

复制代码
server:
  port: 8001            #端口号
  
mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml        # mybatis配置文件所在路径
  type-aliases-package: com.jincou.springcloud.entities     # 所有Entity别名类所在包
  mapper-locations:
  - classpath:mybatis/mapper/**/*.xml                       # mapper映射文件
    
spring:
   application:
    name: serverspringcloud-dept             #这个名字很重要后期如果注入eureka就很重要
   datasource:
    type: com.alibaba.druid.pool.DruidDataSource            # 当前数据源操作类型
    driver-class-name: org.gjt.mm.mysql.Driver              # mysql驱动包
    url: jdbc:mysql://localhost:3306/cloudDB01            # 数据库名称
    username: root
    password: root
    dbcp2:
      min-idle: 5                                           # 数据库连接池的最小维持连接数
      initial-size: 5                                       # 初始化连接数
      max-total: 5                                          # 最大连接数
      max-wait-millis: 200                                  # 等待连接获取的最大超时时间
复制代码

3、MySQL表信息

4、DAO接口信息

复制代码
@Mapper
public interface DeptDao
{
    public boolean addDept(Dept dept);//添加部门

    public Dept findById(Long id);   //通过id找该部门数据

    public List<Dept> findAll();     //查看所有部门
}
复制代码

 5、Controller层类

复制代码
@RestController
public class DeptController
{
    @Autowired
    private DeptService service;

   //添加部门接口
    @RequestMapping(value = "/dept/add", method = RequestMethod.POST)
    public boolean add(@RequestBody Dept dept)
    {
        return service.add(dept);
    }
    //通过部门id查找部门信息
    @RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
    public Dept get(@PathVariable("id") Long id)
    {
        return service.get(id);
    }
    //查找所有部门信息
    @RequestMapping(value = "/dept/list", method = RequestMethod.GET)
    public List<Dept> list()
    {
        return service.list();
    }
}
复制代码

 6、测试

 先做个小测试,看数据库连接是否成功,调用api模块是否成功。

说明测试成功!

 

 四、创建部门微服务消费者

主要步骤如图

 

1、pom.xml文件

<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>
<parent>
<groupId>com.jincou.springcloudrest</groupId>
<artifactId>serverspringcloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>serverspringcloud-consumer-dept-80</artifactId>
<description>部门微服务消费者</description>

 

<dependencies>
<dependency><!-- 自己定义的api -->
<groupId>com.jincou.springcloudrest</groupId>
<artifactId>serverspringcloud-api</artifactId>
<version>${project.version}</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 修改后立即生效,热部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
</project>

pom.xml

复制代码
<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>
  <parent>
    <groupId>com.jincou.springcloudrest</groupId>
    <artifactId>serverspringcloud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>serverspringcloud-consumer-dept-80</artifactId>
  <description>部门微服务消费者</description>



    <dependencies>
        <dependency><!-- 自己定义的api -->
              <groupId>com.jincou.springcloudrest</groupId>        
              <artifactId>serverspringcloud-api</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 修改后立即生效,热部署 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>springloaded</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>
</project>
复制代码

2、application.yml

server:
  port: 80

3、ConfigBean配置类

复制代码
@Configuration
public class ConfigBean //    @Configuration配置   ConfigBean = applicationContext.xml
{ 
    @Bean
    public RestTemplate getRestTemplate()
    {
        return new RestTemplate();
    } 
}
复制代码

4、DeptController_Consumer类

复制代码
@RestController
public class DeptController_Consumer
{

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

    /**
     * 使用 使用restTemplate访问restful接口非常的简单粗暴无脑。 (url, requestMap,
     * ResponseBean.class)这三个参数分别代表 REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。
     */
    @Autowired
    private RestTemplate restTemplate;

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

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

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/consumer/dept/list")
    public List<Dept> list()
    {
        return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class);
    }
}
复制代码

5、测试

测试成功,当我调用消费者接口的时候,它会再去调用提供者的接口。

 

五、总结

     整个项目终于跑通,然后再来屡一下思路,其实还是蛮简单的。

  (1)通过maven构建父子工程,一个个子模块就是一个个独立的进程(因为他们端口号都不一样),也就是微服务。

   (2)模块之间的调用只要把你需要的模块放到你的pom.xml中,这样就会打成jar包,就可以供该模块调用。

   (3)接口之间的调用只要通过RestTemplate工具类就可以了。

 

最后本博客GitHub源码:https://github.com/yudiandemingzi/restTemplatestudy

 

转载至:https://www.cnblogs.com/qdhxhz/p/9349950.html

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!