我们会通过一个支付模块来把微服务的各个新老技术全部串联一遍。
先建立一个父工程。
使用本地自己下载的maven。如未下载可以参考maven的下载与安装教程(超详细)_Java修炼记-CSDN博客_maven下载教程。
最后出现Build Success
说明创建成功了。
统一好字符编码,避免后面出现乱码等问题。
开启注解支持。
java编译版本选择为java8.
FileType过滤。这一步选做,可以把项目中不想显示的文件过滤,这样项目看起来会清爽一点。
将父工程的src目录删除,pom.xml配置如下。
<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">
<modelVersion>4.0.0modelVersion>
<groupId>com.wangzhou.springcloudgroupId>
<artifactId>cloud2020artifactId>
<version>1.0-SNAPSHOTversion>
<packaging>pompackaging>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
<junit.version>4.12junit.version>
<log4j.version>1.2.17log4j.version>
<lombok.version>1.16.18lombok.version>
<mysql.version>5.1.49mysql.version>
<druid.version>1.1.17druid.version>
<mybatis.spring.boot.version>2.0.5mybatis.spring.boot.version>
properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-dependenciesartifactId>
<version>2.2.2.RELEASEversion>
<type>pomtype>
<scope>importscope>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-dependenciesartifactId>
<version>Hoxton.SR1version>
<type>pomtype>
<scope>importscope>
dependency>
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-alibaba-dependenciesartifactId>
<version>2.1.0.RELEASEversion>
<type>pomtype>
<scope>importscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>${druid.version}version>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>${mybatis.spring.boot.version}version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>${junit.version}version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
dependencies>
dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<fork>truefork>
<addResources>trueaddResources>
configuration>
plugin>
plugins>
build>
project>
去除maven生命周期中的test
环节。
点击install
,出现Build Success
说明maven与Idea的整合成功了。
我们的需求可以用下图表示:通过order
订单模块调用payment
模块完成支付。
一个微服务的构建过程只要五步:1.建立module 2.改pom 3.写yaml 4.主启动类 5.业务类
(1)建立module
顺带一提,由于我们之前在父工程中使用dependencymanagement
,这里GroupId
与Version
都是自动生成的。
(2)改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>cloud2020artifactId>
<groupId>com.wangzhou.springcloudgroupId>
<version>1.0-SNAPSHOTversion>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>cloud-provider-payment8001artifactId>
<properties>
<maven.compiler.source>8maven.compiler.source>
<maven.compiler.target>8maven.compiler.target>
properties>
<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>druid-spring-boot-starterartifactId>
<version>1.1.10version>
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>
<scope>testscope>
dependency>
dependencies>
project>
这里可能会爆红。
将父工程pom文件mybatis的版本与springboot保持一致即可。
(3)写Yaml
新建application.yml。
# 服务端口号
server:
port: 8001
# 服务名称
spring:
application:
name: cloud-payment-service
#数据库配置
datasource:
type: com.alibaba.druid.pool.DruidDataSource # 当前数据源操作类型
driver-class-name: com.mysql.jdbc.Driver # mysql驱动包
url: jdbc:mysql://localhost:3306/cloud2021?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: 123456
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.wangzhou.springcloud.entities # 所有Bean 别名类所在包
(4)主启动类
package com.wangzhou.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author wangzhou
* @created 2022/03/08
*/
@SpringBootApplication
public class PaymentMain8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8001.class, args);
}
}
(5)业务类
对于后端程序员来说,业务也特别简单,就是五步:建SQL、entities、Dao、Service、Controller。
建数据库
CREATE DATABASE cloud2021;
建表
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
插入数据。
INSERT INTO payment(`serial`)VALUES("张三");
建立entities。在这之前这里先放出项目的目录结构的截图供您参考。
主实体。
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Payment implements Serializable { // 实现Serializable接口方便分布式部署
private Long id; // 数据库中id类型为bigInt,所有这里用Long
private String serial;
}
统一结果返回。
@AllArgsConstructor
@NoArgsConstructor
@Data
//统一结果返回,前端无需关心后端的具体业务,先根据后端返回的状态码与信息判断请求是否成功
public class CommonResult<T> { // 泛型:返回结果类具有通用性,除了Payment也可以是其它类型
private Integer code;
private String message;
private T data;
public CommonResult(Integer code, String message) {
this(code, message, null);
}
}
Dao。
@Mapper // Mybatis 框架推荐使用该注解而不是 @Repository
public interface PaymentDao {
public int create(Payment payment);
public Payment getPaymentById(@Param("id") Long id);
}
Payment.xml
<mapper namespace="com.wangzhou.springcloud.dao.PaymentDao">
<insert id="create" parameterType="Payment" useGeneratedKeys="true" keyProperty="id">
insert into Payment(serial) values (#{serial})
insert>
<resultMap id="BaseMap" type="com.wangzhou.springcloud.entities.Payment">
<id column="id" property="id" javaType="BIGINT"/>
<id column="serial" property="serial" javaType="VARCHAR"/>
resultMap>
<select id="getPaymentById" parameterType="Long" resultMap="BaseMap">
select * from payment where id=#{id}
select>
mapper>
Service
public interface PaymentService {
public int create(Payment payment);
public Payment getPaymentById(@Param("id") Long id);
}
public class PaymentServiceImpl implements PaymentService {
@Resource // java自带注解,也可以进行自动注入
private PaymentDao paymentDao;
@Override
public int create(Payment payment) {
return paymentDao.create(payment);
}
@Override
public Payment getPaymentById(Long id) {
return paymentDao.getPaymentById(id);
}
}
Controller.
@RestController //@Controller + @ResponseBody(将方法的返回结果直接写到responseBody)
@Slf4j //日志
@RequestMapping("/payment")
public class PaymentController {
@Resource
private PaymentService service;
@PostMapping("/created")
public CommonResult create(@RequestBody Payment payment) {
int result = service.create(payment);
log.info("插入结果是:" + result);
if(result > 0) {
return new CommonResult(200, "插入数据成功", 1);
} else {
return new CommonResult(444, "插入数据失败");
}
}
@GetMapping(value = "/get/{id}")
public CommonResult getPaymentById(@PathVariable("id")Long id){
Payment result = service.getPaymentById(id);
log.info("-----查询结果----: "+ result);
if (result != null){
//查询成功
return new CommonResult(200,"查询成功",result);
}else {
return new CommonResult(444,"没有对应记录,查询id: "+id,null);
}
}
}
启动项目。遇到如下问题。
Injection of resource dependencies failed;耐心的看报错信息,看到下图错误。
对应看xml文件。发现jdbcType
写成了javaType
总结:对于异常一定要先耐心读打印出来的异常信息。
查询测试:localhost:8001/payment/get/1
查询结果如下。
插入结果如下。