SpringCloud系列之微服务模块的创建
1、建module在父工程中新建一个module,具体操作不再赘述这里需要注意的地方就在于parent的选择,默认没有选上,需要勾选上Maven,创建完毕后在父工程的pom文件中就会看到自动生成了modules标签。2、改POM由于父工程中已经指定了相关的gav(groupId,version,artifactId),所以子模块中的pom文件会有很多地方不需要写version以及groupId&l
文章目录
1、建module
在父工程中新建一个
module
,具体操作不再赘述
这里需要注意的地方就在于
parent
的选择,默认没有选上,需要勾选上Maven
,创建完毕后在父工程的pom
文件中就会看到自动生成了modules
标签。
2、改POM
由于父工程中已经指定了相关的
gav(groupId,version,artifactId)
,所以子模块中的pom
文件会有很多地方不需要写version
以及groupId
<?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>SpringCloudDemo</artifactId>
<groupId>com.phz.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>CloudProviderPayment8001</artifactId>
<dependencies>
<!--web和actuator在spring-boot中几乎是绑定到一块的,后面的图形化显示和坐标监控,图形处理都非常重要-->
<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>
<!--mybatis和spring-boot的整合-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!--阿里巴巴的德鲁伊druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<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>
</dependency>
</dependencies>
</project>
3、写YML
在子
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
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
编写完毕就是Mybatis
的Mapper
文件
注意要对应yml
配置文件声明的要求创建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">
<mapper namespace="com.phz.dao.PaymentDao">
<!--如果数据库插入成功应该返回一个结果 所以useGeneratedKeys应该为true,指定返回的keyProperty为id-->
<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
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);
}
}
6、测试
整个工程目录结构如下
至此第一个微服务模块建立完毕,其他模块可以按照相同的步骤创建。
7、同样的步骤创建第二个module
由于跟上面步骤一致,所以不再详述,主要过程代码仍然贴出来
①、建module
同样的步骤,只需要注意
Parent
选择正确
②、POM
<?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>SpringCloudDemo</artifactId>
<groupId>com.phz.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>CloudCusumerOrder80</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.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</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
Ⅱ、RestTemplate
简要介绍什么是
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();
}
}
Ⅲ、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、再次测试
将
Payment
和Order
模块同时开启
访问查询方法
访问插入方法
更多推荐
所有评论(0)