SpringCloud之微服务模块的创建

1、建module

在父工程中新建一个module,具体操作不再赘述

SpringCloud之微服务模块的创建_第1张图片

这里需要注意的地方就在于parent的选择,默认没有选上,需要勾选上Maven,创建完毕后在父工程的pom文件中就会看到自动生成了modules标签。

SpringCloud之微服务模块的创建_第2张图片

2、改POM

由于父工程中已经指定了相关的gav(groupId,version,artifactId),所以子模块中的pom文件会有很多地方不需要写version以及groupId


<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>SpringCloudDemoartifactId>
        <groupId>com.phz.springcloudgroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>CloudProviderPayment8001artifactId>
    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
        dependency>
    dependencies>
project>

3、写YML

在子moduleresources目录下新建application.yml配置文件

SpringCloud之微服务模块的创建_第3张图片

保证文件前面有个绿叶标志,如果不是,尝试在mavenreimport以下即可

server:
  port: 8001

spring:
  application:
    name: cloud-payment-service
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql:///cloud?serverTimezone=Asia/Shanghai&useSSL=false&useUnicode=true&characterEncoding=utf8
    username: root
    password: 123456

mybatis:
  mapperLocations: classpath:mapper/*.xml
  type-aliases-package: com.phz.entities

4、主启动

package com.phz;

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

/**
 * @author PengHuAnZhi
 * @createTime 2021/1/31 17:35
 * @projectName SpringCloudDemo
 * @className PaymentMain8001.java
 * @description TODO
 */
@SpringBootApplication
public class PaymentMain8001 {
     
    public static void main(String[] args) {
     
        SpringApplication.run(PaymentMain8001.class, args);
    }
}

5、业务类

以上4步就可以成功的创建一个可用的模块了,接下来就是些业务逻辑代码的编写

①建表

首先创建数据库表,这里创建一张订单表,一个订单编号,一个订单信息

CREATE TABLE `payment`(
	`id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
	`serial` VARCHAR(200) DEFAULT'',
	PRIMARY KEY(`id`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

②创建实体Bean

创建和数据库对应的实体Bean

/**
 * @author PengHuAnZhi
 * @createTime 2021/1/31 17:48
 * @projectName SpringCloudDemo
 * @className Payment.java
 * @description TODO
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Payment implements Serializable {
     
    //订单流水
    private Long id;
    private String serial;
}

③封装实体Bean

采用前后端分离的思想,将实体Bean再次封装,供前端接收

/**
 * @author PengHuAnZhi
 * @createTime 2021/1/31 17:51
 * @projectName SpringCloudDemo
 * @className CommonResult.java
 * @description TODO
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
//前后端分离给前端返回的不是一个单纯的Payment类,我们还需要对其进行封装一下
public class CommonResult<T> {
     //泛型是为了让所有返回的对象都通用
    //返回的代码
    private Integer code;
    //返回的消息
    private String message;
    //返回的对象
    private T data;

    //有时候我们传递过去的返回对象中的T是一个null的,这里为了更好的代码逻辑,定义一个双参的构造方法
    public CommonResult(Integer code, String message) {
     
        this(code, message, null);
    }
}

④Mapper

实体Bean编写完毕就是MybatisMapper文件

注意要对应yml配置文件声明的要求创建Mapper文件

SpringCloud之微服务模块的创建_第4张图片



<mapper namespace="com.phz.dao.PaymentDao">
    
    <insert id="insert" parameterType="Payment" useGeneratedKeys="true" keyProperty="id">
        insert into payment(serial) values (#{serial});
    insert>
    <resultMap id="BaseResultMap" type="com.phz.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>

⑤Dao接口

编写Dao层接口

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/1 14:33
 * @projectName SpringCloudDemo
 * @className PaymentDao.java
 * @description TODO
 */
@Mapper
public interface PaymentDao {
     
    //只写上两个常用的方法重点不在这儿
    int insert(Payment payment);

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

⑥Service接口

Dao层写完了就是Service层接口

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/1 14:49
 * @projectName SpringCloudDemo
 * @className PaymentService.java
 * @description TODO
 */
public interface PaymentService {
     
    //只写上两个常用的方法重点不在这儿
    public int insert(Payment payment);

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

⑦ServiceImpl

Service接口实现类

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/1 14:50
 * @projectName SpringCloudDemo
 * @className PaymentServiceImpl.java
 * @description TODO
 */
@Service
public class PaymentServiceImpl implements PaymentService {
     
    @Resource
    PaymentDao paymentDao;

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

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

⑧Controller

DaoService写完后就是Controller

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/1 14:53
 * @projectName SpringCloudDemo
 * @className PaymentController.java
 * @description TODO
 */
@RestController
@Slf4j
public class PaymentController {
     
    @Resource
    PaymentService paymentService;

    @PostMapping(value = "/payment/insert")
    public CommonResult<Integer> insert(Payment payment) {
     
        int result = paymentService.insert(payment);
        log.info("插入结果:" + result);
        return result > 0 ? new CommonResult<Integer>(200, "插入数据成功", result) : new CommonResult<Integer>(444, "插入数据失败", null);
    }

    @GetMapping(value = "payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
     
        Payment payment = paymentService.getPaymentById(id);
        log.info("查询结果:" + payment);
        return payment != null ? new CommonResult<>(200, "查询成功", payment) : new CommonResult<>(444, "没有这条数据,id为:" + id, null);
    }
}

6、测试

SpringCloud之微服务模块的创建_第5张图片

SpringCloud之微服务模块的创建_第6张图片

SpringCloud之微服务模块的创建_第7张图片

整个工程目录结构如下

SpringCloud之微服务模块的创建_第8张图片

至此第一个微服务模块建立完毕,其他模块可以按照相同的步骤创建。

7、同样的步骤创建第二个module

由于跟上面步骤一致,所以不再详述,主要过程代码仍然贴出来

①、建module

同样的步骤,只需要注意Parent选择正确

SpringCloud之微服务模块的创建_第9张图片

②、POM


<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>SpringCloudDemoartifactId>
        <groupId>com.phz.springcloudgroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>CloudCusumerOrder80artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
        dependency>
    dependencies>
project>

③、YML

server:
  port: 8002

④、主启动

package com.phz;

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

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/1 20:05
 * @projectName SpringCloudDemo
 * @className OrderMain80.java
 * @description TODO
 */
@SpringBootApplication
public class OrderMain80 {
     
    public static void main(String[] args) {
     
        SpringApplication.run(OrderMain80.class, args);
    }
}

⑤、业务类

Ⅰ、实体bean

SpringCloud之微服务模块的创建_第10张图片

Ⅱ、RestTemplate

简要介绍什么是RestTemplate

  • RestTemplate提供了多种编写访问远程Http服务的方法,是一种简单便捷的访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具集

SpringCloud之微服务模块的创建_第11张图片

注入Spring容器

package com.phz.entities.config;

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

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/1 20:14
 * @projectName SpringCloudDemo
 * @className ApplicationContextConfig.java
 * @description TODO
 */
@Configuration
public class ApplicationContextConfig {
     
    @Bean
    public RestTemplate getRestTemplate() {
     
        return new RestTemplate();
    }
}

Ⅲ、Controller

package com.phz.controller;

import com.phz.entities.CommonResult;
import com.phz.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author PengHuAnZhi
 * @createTime 2021/2/1 20:11
 * @projectName SpringCloudDemo
 * @className OrderController.java
 * @description TODO
 */
@RestController
@Slf4j
public class OrderController {
     
    private static final String PAYMENT_URL = "http://localhost:8001";
    @Resource
    RestTemplate restTemplate;

    //由于是客户端,发的都是get请求
    @GetMapping("/consumer/payment/insert")
    public CommonResult insert(Payment payment) {
     
        //参数分别为REST请求地址、请求参数,HTTP响应被转换成的对象类型
        return restTemplate.postForObject(PAYMENT_URL + "/payment/insert", payment, CommonResult.class);
    }

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

8、再次测试

PaymentOrder模块同时开启

SpringCloud之微服务模块的创建_第12张图片

访问查询方法

SpringCloud之微服务模块的创建_第13张图片

访问插入方法

SpringCloud之微服务模块的创建_第14张图片

SpringCloud之微服务模块的创建_第15张图片

你可能感兴趣的:(java,spring,cloud,微服务)