In the last part of Spring Cloud(02) — Building order-Payment microservice module, we have built the parent project. Now we need to build sub-modules in the parent project. First, we will build the service provision module, which is the payment module, and then we will build the service consumer module, which is the consumer order module.

1. Build the payment module

1. Environment construction

Create a submodule in the parent project: cloud-Provider-Payment8001

Modules: / poM/poM

<modules>
  <module>cloud-provider-payment8001</module>
</modules>
Copy the code

2. Import dependencies in the POM of submodules

<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>
    <! -- Hot deployment -->
    <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>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
</dependencies>
Copy the code

3. Write configuration files

server:
  port: 8001

spring:
  application:
    name: cloud-payment-service

Copy the code

4, write the main boot class

@SpringBootApplication
public class PaymentMain8001 {
    public static void main(String[] args) { SpringApplication.run(PaymentMain8001.class,args); }}Copy the code

2. Write business

1, build database build table

CREATE TABLE `db01`.`payment`( 
 `id` BIGINT(50) NOT NULL AUTO_INCREMENT, 
 `serial` VARCHAR(50), 
 PRIMARY KEY (`id`) 
 ) ENGINE=INNODB CHARSET=utf8 COLLATE=utf8_general_ci; 
 
Copy the code

2. Idea connects to database

3. Write database configuration files

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/db01? useUnicode=true&characterEncoding=utf-8&useSSl=false
    username: root
    password: 19990802
Copy the code

4. Write entity classes

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

Write a JSON wrapper

@Data
@AllArgsConstructor
@NoArgsConstructor
// Pass it to the front-end JSON wrapper
public class CommonResult<T> {
    
    private Integer code;  // Exception code
    private String message;// Exception information
    private T      data;   
    
    // A two-argument constructor
    public CommonResult(Integer code, String message) {
        this(code, message, null); }}Copy the code

5. Write dao layer interfaces

@Mapper
public interface PaymentDao {

    public int create(Payment payment);


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

Mapper. XML Mapping file


      
<! DOCTYPEmapper
        PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cheng.springcloud.dao.PaymentDao">

    <! Select * from database where primary key ID is generated -->
    <insert id="create" parameterType="Payment" useGeneratedKeys="true" keyProperty="id">
        insert into Payment (serial) values (#{serial})
    </insert>

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

    <select id="getPaymentById" parameterType="Long" resultMap="BaseMap">
        select * from Payment where id=#{id}
    </select>

</mapper>
Copy the code

Add myBatis configuration

mybatis:
  type-aliases-package: com.cheng.springcloud.pojo
  mapper-locations: classpath:mapper/*.xml
Copy the code

6. Write the business layer

Service layer interface

public interface PaymentService {

    public int create(Payment payment);


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

}
Copy the code

Business layer implementation class

@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) {
        returnpaymentDao.getPaymentById(id); }}Copy the code

7. Write controller

@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @PostMapping("/payment/create")
    public CommonResult create(Payment payment){
        int result = paymentService.create(payment);

        log.info("======= Add result ="+result);

        if (result > 0) {return new CommonResult(200."Add executed successfully",result);
        }else {
            return new CommonResult(500."Add execution failed".null); }}@GetMapping("/payment/create/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);

        log.info("======= Query Result ="+payment);

        if(payment ! =null) {return new CommonResult(200."Query executed successfully",payment);
        }else {
            return new CommonResult(500."Query id as"+id+"Execution failed".null); }}}Copy the code

Insert data into table Payment:

insert into payment(serial) values ('jingdong')
Copy the code

Test the getPaymentById method:

Access request: localhost: 8001 / payment/get / 1

Access request: localhost: 8001 / payment/get / 2

Test the CREATE method: Since the create method is submitted by post, it is recommended to test with Postman.

Access request: localhost: 8001 / payment/create? serial

Test successful!

2. Build the consumer order module

1. Environment construction

Create a submodule in the parent project: cloud-consumer-Order8001

2. Import dependencies:

<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>
    <! -- Hot deployment -->
    <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>

    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
</dependencies>
Copy the code

3. Configure the file application.yml

server:
  port: 80
Copy the code

4, the main boot class

@SpringBootApplication
public class OrderMain80 {
    public static void main(String[] args) { SpringApplication.run(OrderMain80.class,args); }}Copy the code

2. Write business

1. Copy the entity class in the payment module to the consumer module

2. Since the consumer only needs to access the services provided by the service provider, all you need to do is write the controller

Here we use RestTemplate for remote access. RestTemplate is an HTTP request tool supported by Spring3.0. It is a simple and convenient template class for accessing restful services. It is a set of client template tools provided by Spring for accessing Rest services.

It provides templates for common REST request schemes such as GET request, POST request, PUT request, DELETE request and common request execution methods exchange and Execute.

Write a configuration class to inject the RestTemplate into the container:

@Configuration
public class ConfigBean {

    @Bean
    public RestTemplate getRestTemplate(a){
        return newRestTemplate(); }}Copy the code

Write the controller to access the remote service:

package com.cheng.springcloud.controller;

import com.cheng.springcloud.pojo.CommonResult;
import com.cheng.springcloud.pojo.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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;

@RestController
@Slf4j
public class OrderController {


    // Extract the remote address prefix
    public static final String REST_URL_PREFIX = "http://localhost:8001";

    @Resource
    private RestTemplate restTemplate;


    //postForObject parameter: url+ method parameter + return value of the class object, server to use what request, client to use what request
    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment){
        return restTemplate.postForObject(REST_URL_PREFIX+"/payment/create",payment,CommonResult.class);

    }

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

test

Start the payment module first, then the consumer module

1. Test the query operation

Access request http://localhost/consumer/payment/get/2: to see if can access to the services provided by the service provider,

Successful visit!

2. Test the add operation:

Access request: http://localhost/consumer/payment/create? Serial =”455″;

Ok, so let’s go back to our database and see,

The data we added was null, but in the request above, we passed the data, why is null displayed?

This is because we’re not using @requestBody to accept json data,

The @RequestBody function is to convert jSON-formatted data into Java objects.

Solution: Add @requestBody to the body of the method providing the service:

@PostMapping(value = "/payment/create")
public CommonResult create(@RequestBody Payment payment){
    int result = paymentService.create(payment);

    log.info("======= Add result ="+result);

    if (result > 0) {return new CommonResult(200."Add executed successfully",result);
    }else {
        return new CommonResult(500."Add execution failed".null); }}Copy the code

Using hot deploy quick Build projects,

Go to http://localhost/consumer/payment/create? Serial = null;

Look at the database

Added successfully!

3. Engineering reconstruction

In both of our modules above, we have the same directory, the POJO directory, which would be redundant in normal development, so we’ll take it out.

Create a new module cloud-api-Commons

2. Import dependencies

<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 is a small and complete Java tool library -->
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>
Copy the code

3. Copy the poJO directory to cloud-api-Commons module

Run maven clean and install

5. Pay 8001 for transformation and 80 for order

Remove the poji directory from both modules, then add the following dependencies to both modules:

<! -- Introduce an API module where you can use entity classes -->
<dependency>
    <groupId>com.cheng.springcloud</groupId>
    <artifactId>cloud-api-commons</artifactId>
    <version>${project.version}</version>
</dependency>
Copy the code

Current engineering sample drawing: