03-06、SpringCloud第六章,升级篇,升级概述与Rest微服务案例构建

SpringCloud第六章,升级篇,升级概述与Rest微服务案例构建

一、Springcloud升级之后的变动

发现springcloud升级之后,原来的各个框架都有所变化。

二、Rest微服务构建案例工程

以订单模块做一个微服务通用案例、Consumer消费者[order]通过rest调用Provider生产者[payment]提供的服务

结构:

xml 复制代码
cloud-2020
	cloud-api-commons				公共模块
	cloud-provider-payment-8001     微服务提供者--提供订单支付功能
	cloud-consumer-order-80			微服务消费者--订单

1、父工程

new maven project

XML 复制代码
groupID  			com.lee.springcloud
artifact id			cloud_2020
packaging			pom

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.lee.springcloud</groupId>
  <artifactId>cloud_2020</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>
  <name>Maven</name>
  <url>http://maven.apache.org/</url>
  <inceptionYear>2001</inceptionYear>

  <!--统一版本管理-->
  <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>
    <mysql.version>5.1.47</mysql.version>
    <druid.version>1.1.16</druid.version>
    <mybatis.spring.boot.version>1.3.2</mybatis.spring.boot.version>
  </properties>

  <!-- 子模块继承之后,提供作用:锁定版本+子模块不用写groupId和version  -->
  <dependencyManagement>
    <dependencies>

      <!--  springboot 2.2.2    -->
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>2.2.2.RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <!--  springcloud cloud Hoxton.SR1   -->
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>Hoxton.SR1</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <!--  springcloud cloud alibaba 2.1.0.RELEASE    -->
      <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-alibaba-dependencies</artifactId>
        <version>2.1.0.RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>


      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql.version}</version>
      </dependency>

      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>${druid.version}</version>
      </dependency>

      <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>${mybatis.spring.boot.version}</version>
      </dependency>

      <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
      </dependency>

      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
      </dependency>

      <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>${lombok.version}</version>
        <optional>true</optional>
      </dependency>

    </dependencies>
  </dependencyManagement>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <fork>true</fork>
          <addResources>true</addResources>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

2、cloud-provider-payment-8001子模块

new maven module

XML 复制代码
moduleName   cloud-provider-payment-8001
parentProject  cloud_2020
groupId      com.lee.springcloud
artifactId    cloud_2020
packaging     jar

创建完成后 父工程POM文件会多了个标签

父pom文件

XML 复制代码
<modules>
    <module>cloud-provider-payment-8001</module>
</modules>

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">
    <parent>
        <artifactId>cloud_2020</artifactId>
        <groupId>com.lee.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>cloud-provider-payment-8001</artifactId>
    <packaging>jar</packaging>


    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

    </dependencies>


</project>

application.yml

yml 复制代码
server:
  port: 8001


spring:
  application:
    name: cloud-payment-service
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: org.gjt.mm.mysql.Driver
    url: jdbc:mysql://localhost:3306/cloud2020?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: admin123


mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.lee.springcloud.entities
  ##configuration:
    ##log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  打印SQL日志

主启动类

java 复制代码
package com.lee.springcloud;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
//扫描mybatis的dao接口
@MapperScan("com.lee.springcloud.dao")
public class PaymentMain8001 {

    public static void main(String[] args) {
        SpringApplication.run(PaymentMain8001.class,args);
    }
}

entities

后面做项目优化的时候会将entities文件放入cloud-api-commons公共模块中

java 复制代码
package com.lee.springcloud.entities;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.io.Serializable;

/**
 * 支付类
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Payment implements Serializable {
    private static final long serialVersionUID = -863569077381025504L;

    private Long id;

    private String serial;

}
java 复制代码
package com.lee.springcloud.entities;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
 * 统一前端返回类
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class CommonResult<T> {

    private Integer code;
    private String message;
    private T data;

    public CommonResult(Integer code, String message) {
        this(code, message, null);
    }
}

paymentMapper.xml

xml 复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lee.springcloud.dao.PaymentDao">

    <insert id="create" parameterType="Payment" useGeneratedKeys="true" keyProperty="id">
        insert into payment (serial) values (#{serial});
    </insert>

    <resultMap id="BaseResultMap" type="Payment">
        <id column="id" property="id" jdbcType="BIGINT"/>
        <id column="serial" property="serial" jdbcType="VARCHAR"/>
    </resultMap>

    <select id="getPaymentById" parameterType="Long" resultMap="BaseResultMap">
        select * from payment where id = #{id};
    </select>
</mapper>

DAO

java 复制代码
package com.lee.springcloud.dao;

import com.lee.springcloud.entities.Payment;
import org.apache.ibatis.annotations.Param;
/**
 * 因为在主启动类上添加了mapperScan注解,这里就无须再增加mapper注解了
 * 两者二选其一
 */
public interface PaymentDao {

    int create(Payment payment);

    Payment getPaymentById(@Param("id") Long id);
}

service

java 复制代码
package com.lee.springcloud.service;

import com.lee.springcloud.entities.Payment;

public interface PaymentService{

    int create(Payment payment);

    Payment getPaymentById(Long id);

}
java 复制代码
package com.lee.springcloud.service.impl;

import com.lee.springcloud.dao.PaymentDao;
import com.lee.springcloud.entities.Payment;
import com.lee.springcloud.service.PaymentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Resource
    private PaymentDao paymentDao;

    @Override
    public int create(Payment payment) {
        return paymentDao.create(payment);
    }

    @Override
    public Payment getPaymentById(Long id) {
        return paymentDao.getPaymentById(id);
    }
}

controller

JAVA 复制代码
package com.lee.springcloud.controller;

import com.lee.springcloud.entities.CommonResult;
import com.lee.springcloud.entities.Payment;
import com.lee.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Slf4j
@RequestMapping("/payment")
@RestController
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @PostMapping("/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("插入数据的ID:\t" + payment.getId());
        log.info("插入结果:" + result);
        if (result > 0) {
            return new CommonResult(200, "插入数据成功 :" +result);
        } else {
            return new CommonResult(444, "插入数据失败", null);
        }
    }

    @GetMapping("/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("***查询结果O(∩_∩)O哈哈~:" + payment);
        if (payment != null) {
            return new CommonResult(200, "查询数据成功 :" + payment);
        } else {
            return new CommonResult(444, "没有对应记录", null);
        }
    }
}

sql

sql 复制代码
CREATE TABLE `payment`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `serial` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '支付流水号',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '支付表' ROW_FORMAT = Dynamic;

测试:

XML 复制代码
1、GET   http://localhost:8001/payment/get/1

2、POST  http://localhost:8001/payment/create
body:
{
	"serial":"003"
}

3、cloud-consumer-order-80

new maven module

XML 复制代码
moduleName   cloud-consumer-order-80
parentProject  cloud_2020
groupId      com.lee.springcloud
artifactId    cloud_2020
packaging     jar

创建完成后 父工程POM文件会多了个标签

父pom文件

XML 复制代码
<modules>
    <module>cloud-provider-payment-8001</module>
    <module>cloud-consumer-order-80</module>
</modules>

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">
    <parent>
        <groupId>com.lee.springcloud</groupId>
        <artifactId>cloud_2020</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>cloud-consumer-order-80</artifactId>
    <packaging>jar</packaging>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

    </dependencies>


</project>

application.yml

yaml 复制代码
server:
  port: 80

主启动类

java 复制代码
package com.lee.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * consumer主启动类
 */
@SpringBootApplication
public class OrderMain80 {

    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class,args);
    }
}

配置类

主要是为了引入restTemplate工具,RestTemplate提供了多种便捷访问远程HTTP服务的方法,

是spring提供的用于访问rest服务的客户端模板工具集,类似HttpClient

java 复制代码
package com.lee.springcloud.config;

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

/**
 * 配置类
 */
@Configuration
public class ApplicationContextConfig {

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

}

entities

JAVA 复制代码
payment类和CommonResult类,同上cloud-provider-payment-8001项目中的一模一样

controller

由于consumer是远程调用provider提供的payment服务,所以这个项目就没有service和Dao层了

java 复制代码
package com.lee.springcloud.controller;

import com.lee.springcloud.entities.CommonResult;
import com.lee.springcloud.entities.Payment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@RequestMapping("/consumer")
public class OrderController {

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

    @Resource
    private RestTemplate restTemplate;

    @PostMapping("/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class, id);
    }



}

测试:

XML 复制代码
GET:   localhost:80/consumer/payment/get/6

POST:   http://localhost:80/consumer/payment/create
body
{
	"serial":"003"
}

三、项目优化:cloud-api-commons

上面两个项目cloud-provider-payment-8001和cloud-consumer-order-80项目都有entities模块,代码重复冗余,所以我们把这个entities提出来放入cloud-api-commons子项目中。它们引用cloud-api-commons即可。

new maven module

XML 复制代码
moduleName   cloud-api-commons
parentProject  cloud_2020
groupId      com.lee.springcloud
artifactId    cloud_2020
packaging     jar

创建完成后 父工程POM文件会多了个标签

父pom文件

XML 复制代码
<modules>
    <module>cloud-provider-payment-8001</module>
    <module>cloud-consumer-order-80</module>
    <module>cloud-api-commons</module>
</modules>

entities

XML 复制代码
payment类和CommonResult类,同上cloud-provider-payment-8001和cloud-consumer-order-80项目中的一模一样

然后分别将上面两个子项目中的entities模块删除

cloud-provider-payment-8001的POM文件

XML 复制代码
<!--cloud-api-commons公共包-->
<dependency>
    <groupId>com.lee.springcloud</groupId>
    <artifactId>cloud-api-commons</artifactId>
    <version>${project.version}</version>
</dependency>

cloud-consumer-order-80的POM文件

XML 复制代码
<!--cloud-api-commons公共包-->
<dependency>
    <groupId>com.lee.springcloud</groupId>
    <artifactId>cloud-api-commons</artifactId>
    <version>${project.version}</version>
</dependency>

四、热部署DevTools

1、各子pom文件中新增

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>

2、父pom文件中新增

xml 复制代码
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>
                <addResources>true</addResources>
            </configuration>
        </plugin>
    </plugins>
</build>

3、IDEA

file->setting->build,execution->compiler

4、在子POM文件中按Ctrl+Alt+Shift+/

5、重启IDEA

相关推荐
BestandW1shEs2 小时前
快速理解微服务中Fegin的概念
微服务
yours_Gabriel2 小时前
【微服务】认识微服务
java·微服务·架构
BestandW1shEs2 小时前
快速理解微服务中Ribbon的概念
微服务·ribbon
奔跑吧邓邓子2 小时前
SpringCloud之Eureka:服务注册与发现全面教程!
spring·spring cloud·eureka
跳跳的向阳花2 小时前
03-07、SpringCloud第七章,升级篇,服务注册与发现Eureka、Zookeeper和Consule
spring cloud·zookeeper·eureka
王·小白攻城狮·不是那么帅的哥·天文3 小时前
Spring框架使用xml方式配置ThreadPoolTaskExecutor线程池,并且自定义线程工厂
xml·java·spring·线程池
小学鸡!4 小时前
Bean的生命周期详解保姆级教程,结合spring boot和spring.xml两种方式讲解,5/7/10大小阶段详细分析
xml·spring boot·spring
运维&陈同学5 小时前
【kafka01】消息队列与微服务之Kafka详解
运维·分布式·后端·微服务·云原生·容器·架构·kafka
日拱一卒无有尽, 功不唐捐终入海5 小时前
html转成图片
spring·maven