二. SpringCloud基本Rest微服務工程搭建

MPolaris發表於2021-01-25

1. 父工程構建

1.1 Maven專案搭建
環境 版本
JDK 1.8
Maven 3.6+
Maven模板 maven-archetype-size
刪除父工程src檔案
1.2 父工程pom檔案

回顧:

① Maven中dependencyManagement和dependencies的區別

​ Maven使用dependencyManagement元素來提供一種管理依賴版本號的方式。通常會在一個組織或者項 目的最頂層的父POM中看到。使用pom.xml中 的dependencyManagement元素能讓所有中引用一個依賴而不用顯示的列出版本號。Maven會沿著父子層次向上找,直到找到一個擁有dependencyManagement元素的專案,然後它就會使用這個元素中指定的版本號。另外如果某個子專案需要使用另外的版本只需要宣告version即可。注意:dependencyManagement裡只是宣告依賴,並不實現引入,因此子專案要顯示的宣告需要的依賴

② Maven中如何跳過單元測試

​ 在Idea的Maven側欄點選閃電圖示,使Maven跳過test生命週期即可。

<?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.polaris</groupId>
    <artifactId>com.polaris.springcloud</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    
    <modules>
    
    </modules>

    <!-- 統一管理jar包版本 -->
    <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.0</mybatis.spring.boot.version>
    </properties>

    <!-- 子模組繼承之後,提供作用:鎖定版本+子modlue不用寫groupId和version  -->
    <dependencyManagement>
        <dependencies>
            <!--spring boot 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>
            <!--spring 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>
            <!--spring 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>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>
                <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. 微服務提供者支付Module模組

cloud-provider-payment8001

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

    <artifactId>cloud-provider-payment8001</artifactId>

    <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>
        <!--mysql-connector-java-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</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>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
2.2 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              # mysql驅動包
    url: jdbc:mysql://mpolaris.top:3306/cloud-test?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: 123456

mybatis:
  mapperLocations: classpath:mapper/*.xml
  type-aliases-package: com.polaris.springcloud.entities    # 所有Entity別名類所在包
2.3 主啟動類
/**
 * @Author polaris
 * @Date 2021/1/21 1:00
 */
@SpringBootApplication
public class PaymentMain {
    public static void main(String[] args) {
        SpringApplication.run(PaymentMain.class,args);
    }
}
2.4 業務類(簡單演示)

建表

image-20210124232157446

entities

主實體 與 Json封裝體

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Payment implements Serializable {
    private Long id;
    private String serial;

}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult<T> {
    private Integer code;
    private String message;
    private T data;

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

dao

介面PaymentDao與mybatis對映檔案PaymentMapper

@Mapper
public interface PaymentDao {

    int save(Payment payment);

    Payment getPaymentById(@Param("id") Long id);
}
<?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.polaris.springcloud.dao.PaymentDao">

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


    <resultMap id="BaseResultMap" type="com.polaris.springcloud.entities.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>

service

介面與實現類

@Service
public class PaymentServiceImpl implements PaymentService {
    @Resource
    private PaymentDao paymentDao;

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

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

controller

@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @PostMapping("/save")
    public CommonResult save(Payment payment) {
        int result = paymentService.save(payment);
        log.info("===> result: " + result);
        if(result > 0) {
            return new CommonResult(200,"儲存到資料庫成功",result);
        }
        return new CommonResult(400,"儲存到資料庫失敗",null);
    }

    @GetMapping("/get/{id}")
    public CommonResult<Payment> save(@PathVariable("id") Long id) {
        Payment paymentById = paymentService.getPaymentById(id);
        log.info("===> payment: " + paymentById);
        if(paymentById != null) {
            return new CommonResult(200,"查詢成功",paymentById);
        }
        return new CommonResult(400,"查詢失敗",null);
    }
}

3. 開啟Devtools熱部署

3.1 聚合父類總工程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.2 當前工程新增devtools依賴
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>
3.3 Idea開啟自動編譯選項
image-20210124211033737
3.4 開啟熱註冊

快捷鍵 ctrl + shift + alt + /,開啟Registry

image-20210124230117788

勾選

image-20210124211807560

重啟Idea,即可測試程式碼時不用手動重啟

注意:該功能只能在開發階段使用,上線前一定要關閉

4. 微服務消費者訂單Module模組

cloud-consumer-order80

4.1 pom.xml
<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>
        <scope>test</scope>
    </dependency>
</dependencies>
4.2 yml配置檔案
server:
  port: 80
4.3 主啟動類
4.4 RestTemplate引入

是什麼

RestTemplate提供了多種便捷 訪問遠端Http服務 的方法,是一種簡單便捷的訪問restful服務模板類,是Spring提供的用於訪問Rest服務的 客戶端模板工具類

如何使用

官網使用:https://docs.spring.io/spring-framework/docs/5.2.2.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html

使用restTemplate訪問restful介面非常的簡單粗暴。

  • url REST請求地址
  • requestMap 請求引數
  • ResponseBean.classs HTTP響應轉換被轉換成的物件型別

config配置類

@Configuration
public class ApplicationContextConfig {
    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}
4.5 業務類

entities

與提供者支付模組一致

controller

@RestController
@Slf4j
@RequestMapping("/consumer")
public class OrderController {
    @Resource
    private RestTemplate restTemplate;

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

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

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> get(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id,
                CommonResult.class);
    }
}
4.6 啟動兩個模組測試

啟動兩個模組沒有出現Run Dashbord的問題

在工程目錄下找.idea資料夾下的workspace.xml新增如下程式碼即可

<component name="RunDashboard">
    <option name="configurationTypes">
      <set>
        <option value="SpringBootApplicationConfigurationType" />
      </set>
    </option>
    <option name="ruleStates">
      <list>
        <RuleState>
          <option name="name" value="ConfigurationTypeDashboardGroupingRule" />
        </RuleState>
        <RuleState>
          <option name="name" value="StatusDashboardGroupingRule" />
        </RuleState>
      </list>
    </option>
</component>
image-20210125000929350

插入成功但是沒有內容的問題

image-20210125001626259

解決:支付模組這裡一定要加@RequestBody註解

@PostMapping("/save")
public CommonResult save(@RequestBody Payment payment) {
	int result = paymentService.save(payment);
	log.info("===> result: " + result);
	if(result > 0) {
	return new CommonResult(200,"儲存到資料庫成功",result);
	}
	return new CommonResult(400,"儲存到資料庫失敗",null);
}

5. 工程重構 - 公共工程模組

5.1 發現問題 - 系統中有重複程式碼 entities
image-20210125002737878
5.2 新建公共工程 cloud-api-common

重複程式碼,公共介面,第三方介面,工具類等都可以放在這裡

pom.xml

Hutool是一個小而全的Java工具類庫,是專案中“util”包友好的替代

<dependencies>
    <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>
    <!-- hutool工具類 -->
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>
5.3 抽取多個模組的共同程式碼
image-20210125003847399

將cloud-api-common安裝到maven倉庫

修改訂單80和支付8001程式碼

  • 刪除各自原先的enntities

  • 各自新增pom內容

<!-- 公共模組 -->
<dependency>
    <groupId>com.polaris</groupId>
    <artifactId>cloud-api-common</artifactId>
    <version>${project.version}</version>
</dependency>

相關文章