在父工程中新建一个
module
,具体操作不再赘述
这里需要注意的地方就在于
parent
的选择,默认没有选上,需要勾选上Maven
,创建完毕后在父工程的pom
文件中就会看到自动生成了modules
标签。
由于父工程中已经指定了相关的
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>
在子
module
中resources
目录下新建application.yml
配置文件
保证文件前面有个绿叶标志,如果不是,尝试在
maven
中reimport
以下即可
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
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);
}
}
以上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
/**
* @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
再次封装,供前端接收
/**
* @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);
}
}
实体
Bean
编写完毕就是Mybatis
的Mapper
文件
注意要对应yml
配置文件声明的要求创建Mapper
文件
<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
层接口
/**
* @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);
}
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);
}
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);
}
}
Dao
和Service
写完后就是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);
}
}
整个工程目录结构如下
至此第一个微服务模块建立完毕,其他模块可以按照相同的步骤创建。
由于跟上面步骤一致,所以不再详述,主要过程代码仍然贴出来
同样的步骤,只需要注意
Parent
选择正确
<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>
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);
}
}
简要介绍什么是
RestTemplate
RestTemplate
提供了多种编写访问远程Http
服务的方法,是一种简单便捷的访问restful
服务模板类,是Spring
提供的用于访问Rest
服务的客户端模板工具集注入
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();
}
}
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);
}
}
将
Payment
和Order
模块同时开启
访问查询方法
访问插入方法