【SpringCloud】02 提供者支付模块构建

微服务模块

1新建Module模块
    |
2更改POM配置信息
    |
3编写YML
    |
4主启动类
    |
5业务类

 

新建module:

 

不勾选骨架创建:
模块名称 Provider-Payment-Port-8001

 

导入依赖项:

<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>

 

创建application.yml文件

server:
  port: 8001

spring:
  application:
    name: provider-payment-service

  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://xxxxxxx:3306/spring_cloud?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=GMT
    username: root 
    password: 123456

mybatis:
  mapperLocations: classpath:xml-mapper/*.xml
  type-aliases-package: cn.dzz.springcloud.entity    # 所有Entity别名类所在包

 

创建程序运行的启动类:

package cn.dzz.springcloud;

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

/**
 * @author ArkD42
 * @file SpringCloud-ATGG-2020
 * @create 2020年08月24日 20:49
 */
@SpringBootApplication
public class ProviderPaymentServicePort8001Application {
    public static void main(String[] args) {
        SpringApplication.run(ProviderPaymentServicePort8001Application.class);
    }
}

 

创建支付表:

CREATE TABLE `payment` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `serial` varchar(256) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

创建相应的实体类:

package cn.dzz.springcloud.entity;

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

import java.io.Serializable;

/**
 * @author ArkD42
 * @file SpringCloud-ATGG-2020
 * @create 2020年08月24日 20:56
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Payment implements Serializable {
    private static final long serialVersionUID = -8406210528540634886L;
    private Long id;
    private String serial;
}

 

创建响应的JSON格式处理类:

package cn.dzz.springcloud.component;

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

/**
 * @author ArkD42
 * @file SpringCloud-ATGG-2020
 * @create 2020年08月24日 20:59
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
public class JsonResult<EntityData> {
    private Integer code;
    private String message;
    private EntityData data;

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

 

创建PaymentDao

package cn.dzz.springcloud.dao;
import cn.dzz.springcloud.entity.Payment;
import org.apache.ibatis.annotations.Param;

/**
 * @author ArkD42
 * @file SpringCloud-ATGG-2020
 * @create 2020年08月24日 21:05
 */
public interface PaymentDao {

    public int insertPayment(Payment payment);
    public Payment queryPaymentById(@Param("id") Long paymentId);
}

这里可以使用@Mapper注解,也可以使用@MapperScan("cn.dzz.springcloud.dao")在启动类上注解

 

配置对应的实体映射器PaymentMapper.xml

<mapper xmlns="http://mybatis.org/schema/mybatis-mapper" namespace="cn.dzz.springcloud.dao.PaymentDao">

    <insert
            id="insertPayment"
            parameterType="cn.dzz.springcloud.entity.Payment"
            useGeneratedKeys="true"
            keyProperty="id"
            keyColumn="id"
    >
        INSET INTO `payment` VALUES(DEFAULT, ?);
    </insert>

    <resultMap id="paymentType" type="cn.dzz.springcloud.entity.Payment">
        <id column="id" property="id" javaType="java.lang.Long" jdbcType="BIGINT" />
        <id column="serial" property="serial" javaType="java.lang.String" jdbcType="VARCHAR" />
    </resultMap>

    <select
            id="queryPaymentById"
            parameterType="java.lang.Long"
            resultMap="paymentType"
    >
        SELECT `id`, `serial` FROM `payment` WHERE `id` = #{id};
    </select>

    <!--<select id="queryPaymentById" resultType="cn.dzz.springcloud.entity.Payment" parameterType="java.lang.Long">-->
    <!--    SELECT `id`, `serial` FROM `payment` WHERE `id` = #{id};-->
    <!--</select>-->
    
</mapper>

<!--
<?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" >
-->

业务接口:

package cn.dzz.springcloud.service;

import cn.dzz.springcloud.entity.Payment;

/**
 * @author ArkD42
 * @file SpringCloud-ATGG-2020
 * @create 2020年08月24日 21:24
 */
public interface PaymentService {
    int addPayment(Payment payment);
    Payment getPaymentById(Long paymentId);
}

实现类:

package cn.dzz.springcloud.service;

import cn.dzz.springcloud.dao.PaymentDao;
import cn.dzz.springcloud.entity.Payment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author ArkD42
 * @file SpringCloud-ATGG-2020
 * @create 2020年08月24日 21:26
 */

@Service
public class PaymentServiceImpl implements PaymentService{

    @Autowired
    private PaymentDao paymentDao;

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

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

 

控制器:

package cn.dzz.springcloud.controller;

import cn.dzz.springcloud.component.JsonResult;
import cn.dzz.springcloud.entity.Payment;
import cn.dzz.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;

/**
 * @author ArkD42
 * @file SpringCloud-ATGG-2020
 * @create 2020年08月24日 21:28
 */
@Controller
@Slf4j
@RequestMapping("payment")
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @PostMapping("create")
    public JsonResult<Payment> createPayment(Payment payment){
        int result = paymentService.addPayment(payment);
        log.info("插入操作结果:" + result);
        if (result > 0) return new JsonResult<Payment>(200, "插入数据成功");
        return new JsonResult<Payment>(500, "插入数据失败");
    }
    @GetMapping("get/{id}")
    public JsonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        Payment paymentById = paymentService.getPaymentById(id);
        log.info("查询操作结果:" + paymentById);
        if (paymentById != null) return new JsonResult<Payment>(200, "查询数据成功");
        return new JsonResult<Payment>(500, "查询数据失败");
    }
}

 

启动主程序测试,发现构建工程报错,无效的源12,则直接更改这个版本配置:

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

然后Mapper-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="cn.dzz.springcloud.dao.PaymentDao">

    <insert
            id="insertPayment"
            parameterType="cn.dzz.springcloud.entity.Payment"
            useGeneratedKeys="true"
            keyProperty="id"
            keyColumn="id"
    >
        INSET INTO `payment` VALUES(DEFAULT, ?);
    </insert>

    <resultMap id="paymentType" type="cn.dzz.springcloud.entity.Payment">
        <id column="id" property="id" javaType="java.lang.Long" jdbcType="BIGINT" />
        <id column="serial" property="serial" javaType="java.lang.String" jdbcType="VARCHAR" />
    </resultMap>

    <select
            id="queryPaymentById"
            parameterType="java.lang.Long"
            resultMap="paymentType"
    >
        SELECT `id`, `serial` FROM `payment` WHERE `id` = #{id};
    </select>

    <!--<select id="queryPaymentById" resultType="cn.dzz.springcloud.entity.Payment" parameterType="java.lang.Long">-->
    <!--    SELECT `id`, `serial` FROM `payment` WHERE `id` = #{id};-->
    <!--</select>-->

</mapper>

<!--
<?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" >
-->

注意上面的Controller,可以对类@RestController,也可以对方法使用@ResponseBody

 

启动测试,访问接口

http://localhost:8001/payment/get/1
{"code":200,"message":"查询数据成功","data":null}

 

如果地址栏输入接口访问插入操作则会405报错:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Aug 24 21:48:51 CST 2020
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
http://localhost:8001/payment/create?serial=aaabbb222

这时候我们需要通过接口模拟请求进行访问测试,使用PostMan

 

插入后查看结果:

发现响应操作异常提醒

Error updating database.  Cause: java.sql.SQLException: No value specified for parameter 1\r\n### The error may exist in file

原来是JDBC的SQL写多了用习惯了问号,改为正常的注入表达式

INSERT INTO `payment` VALUES(DEFAULT, #{serial})

重新测试

{
    "code": 200,
    "message": "插入数据成功",
    "data": null
}

同样的使用Get进行查询操作:

{
    "code": 200,
    "message": "查询数据成功",
    "data": {
        "id": 2,
        "serial": "aaabbb222"
    }
}

DevTools热部署支持:

依赖前提:

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

配置Maven插件支持:

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

对编译器的这些选项勾选设置:

在Pom.xml文件中,按下Ctrl + Shift + Alt + /

弹出这样的一个选项窗口,然后选择第一个注册

向下翻找到,这个:

compiler.automake.allow.when.app.running

除此外还有这个选项:

重启IDEA即可,不过需要注意一点,热部署要求系统性能要好

 

posted @ 2020-08-25 23:28  emdzz  阅读(193)  评论(0)    收藏  举报