文章目录
- ①. 从Boot和Cloud版本选型
- ②. SpringCloud生态底层
- ③. 整合knife4j - swagger3
- ④. 父工程项目搭建
- ⑤. 支付微服务 - 8001
- ⑥. 订单微服务 - consumer80
- ⑦. 热部署Devtools(开发阶段)
- ⑧. 测试Run DashBord
①. 从Boot和Cloud版本选型
- ①. 结论:本次Java、cloud、boot、cloud alibaba各个依赖
- ②. Springboot版本选择
- git源码地址
- 官网看Boot版本
- SpringBoot3.0崛起
-
③. Springcloud版本选择:git源码地址
-
④. SpringCloud的版本关系
- Spring Cloud 采用了英国伦敦地铁站的名称来命名,并由地铁站名称字母A-Z依次类推的形式来发布迭代版本
- SpringCloud是一个由许多子项目组成的综合项目,各子项目有不同的发布节奏。为了管理SpringCloud与各子项目的版本依赖关系,发布了一个清单,其中包括了某个SpringCloud版本对应的子项目版本。为了避免SpringCloud版本号与子项目版本号混淆,SpringCloud版本采用了名称而非版本号的命名,这些版本的名字采用了伦敦地铁站的名字,根据字母表的顺序来对应版本时间顺序。例如Angel是第一个版本, Brixton是第二个版本
- 当SpringCloud的发布内容积累到临界点或者一个重大BUG被解决后,会发布一个"service releases"版本,简称SRX版本,比如Greenwich.SR2就是SpringCloud发布的Greenwich版本的第2个SRX版本
- ⑤. springcloud(截至2023.12.12)
- ⑥. SpringCloud Alibaba官网Github说明
②. SpringCloud生态底层
- ①. 2024年,SpringCloud生态底层技术已经发生了较大改变。随着Eureak/Ribbon/Hystrix/Sleuth/Zuul等陆续已宣布停止更新,其他技术随之上位将其替代
- ②. 各个组件的作用
服务场景 | 支撑技术 |
---|---|
服务注册与发现 | Consul、Nacos(阿里系) |
分布式配置管理 | Consul、Nacos(阿里系) |
服务调用与负载均衡 | LoadBalancer、OpenFeign |
服务熔断和降级 | Resilience4j、Sentinel(阿里系) |
服务链路追踪 | Micrometer Tracing + Zipkin |
服务网关 | Gateway |
分布式事务 | Seata(阿里系) |
- ③. 下面我们做一个简单的需求:下订单、调用支付
③. 整合knife4j - swagger3
- ①. 后续项目使用的springBoot版本为3.2.0,依赖导入最新的knife4j 4.4.0(以下是一些常见的Spring Boot版本及其对应的Knife4j版本兼容推荐)
-
②. Knife4j官方文档
-
③. 引入yaml文件、yaml文件具体配置详解
#knife4j配置
knife4j:#是否启用增强设置enable: true#开启生产环境屏蔽production: false#是否启用登录认证basic:enable: trueusername: adminpassword: 123456setting:language: zh_cn# 是否开启界面中对某接口的版本控制,如果开启,后端变化后Ui界面会存在小蓝点enable-version: true# 是否显示界面中SwaggerModel功能enable-swagger-models: true# 重命名SwaggerModel名称,默认swagger-model-name: 支付提供模块
- ④. 在controller层面进行配置
@RestController
@Tag(name = "支付微服务模块", description = "支付CRUD")
@Slf4j
public class PayController {@PostMapping(value = "/pay/add")@Operation(summary = "新增(新增支付流水方法,json串做参数)")public ResultData<String> addPay(@RequestBody Pay pay){System.out.println(pay.toString());int i = payService.add(pay);return ResultData.success("成功插入记录,返回值:"+i);}
}
@Operation(summary = "普通body请求")@PostMapping("/body")public ResponseEntity<FileResp> body(@RequestBody FileResp fileResp){return ResponseEntity.ok(fileResp);}@Operation(summary = "普通body请求+Param+Header+Path")@Parameters({@Parameter(name = "id",description = "文件id",in = ParameterIn.PATH),@Parameter(name = "token",description = "请求token",required = true,in = ParameterIn.HEADER),@Parameter(name = "name",description = "文件名称",required = true,in=ParameterIn.QUERY)})@PostMapping("/bodyParamHeaderPath/{id}")public ResponseEntity<FileResp> bodyParamHeaderPath(@PathVariable("id") String id,@RequestHeader("token") String token, @RequestParam("name")String name,@RequestBody FileResp fileResp){fileResp.setName(fileResp.getName()+",receiveName:"+name+",token:"+token+",pathID:"+id);return ResponseEntity.ok(fileResp);}
- ⑤. 浏览器输入:http://ip:port/doc.html
④. 父工程项目搭建
- ①. 约定 > 配置 > 编码
步骤:
(1). 聚合总工程名字
(2). 字符编码
(3). 注解生效激活
(4). java编译版本选8
(5). File Type过滤(可选)
- ②. 聚合总父工程名字mscloudV5,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"><modelVersion>4.0.0</modelVersion><groupId>com.xiaozhi.cloud</groupId><artifactId>mscloudV5</artifactId><version>1.0-SNAPSHOT</version><modules><module>cloud-provider-payment8001</module><module>cloud-api-commons</module><module>cloud-consumer-order80</module></modules><packaging>pom</packaging><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><hutool.version>5.8.22</hutool.version><lombok.version>1.18.26</lombok.version><druid.version>1.1.20</druid.version><mybatis.springboot.version>3.0.2</mybatis.springboot.version><mysql.version>8.0.11</mysql.version><swagger3.version>2.2.0</swagger3.version><mapper.version>4.2.3</mapper.version><fastjson2.version>2.0.40</fastjson2.version><persistence-api.version>1.0.2</persistence-api.version><spring.boot.test.version>3.1.5</spring.boot.test.version><spring.boot.version>3.2.0</spring.boot.version><spring.cloud.version>2023.0.0</spring.cloud.version><spring.cloud.alibaba.version>2022.0.0.0-RC2</spring.cloud.alibaba.version><knife4j.version>2.0.9</knife4j.version></properties><dependencyManagement><dependencies><!--springboot 3.2.0--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>${spring.boot.version}</version><type>pom</type><scope>import</scope></dependency><!--springcloud 2023.0.0--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring.cloud.version}</version><type>pom</type><scope>import</scope></dependency><!--springcloud alibaba 2022.0.0.0-RC2--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-dependencies</artifactId><version>${spring.cloud.alibaba.version}</version><type>pom</type><scope>import</scope></dependency><!--SpringBoot集成mybatis--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>${mybatis.springboot.version}</version></dependency><!--Mysql数据库驱动8 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version></dependency><!--SpringBoot集成druid连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>${druid.version}</version></dependency><!--通用Mapper4之tk.mybatis--><dependency><groupId>tk.mybatis</groupId><artifactId>mapper</artifactId><version>${mapper.version}</version></dependency><!--persistence--><dependency><groupId>javax.persistence</groupId><artifactId>persistence-api</artifactId><version>${persistence-api.version}</version></dependency><!-- fastjson2 --><dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2</artifactId><version>${fastjson2.version}</version></dependency><!-- swagger3 调用方式 http://你的主机IP地址:5555/swagger-ui/index.html --><dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-starter-webmvc-ui</artifactId><version>${swagger3.version}</version></dependency><!--hutool--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>${hutool.version}</version></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>${lombok.version}</version><optional>true</optional></dependency><!-- spring-boot-starter-test --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><version>${spring.boot.test.version}</version><scope>test</scope></dependency><!-- 引入自己定义的api通用包 --><dependency><groupId>com.xiaozhi.cloud</groupId><artifactId>cloud-api-commons</artifactId><version>1.0-SNAPSHOT</version></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.4.RELEASE</version><configuration><fork>true</fork><addResources>true</addResources></configuration></plugin></plugins></build>
</project>
- ③. mysql驱动说明
1. mysql5.7
# mysql5.7---JDBC四件套
jdbc.driverClass = com.mysql.jdbc.Driver
jdbc.url= jdbc:mysql://localhost:3306/db2024?useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.user = root
jdbc.password =123456
# Maven的POM文件处理
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version>
</dependency>2. mysql8.0---JDBC四件套
jdbc.driverClass = com.mysql.cj.jdbc.Driver
jdbc.url= jdbc:mysql://localhost:3306/db2024?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
jdbc.user = root
jdbc.password =123456# Maven的POM
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version>
</dependency>
⑤. 支付微服务 - 8001
- ①. 新建项目 - cloud-payment-service8001,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>mscloudV5</artifactId><groupId>com.xiaozhi.cloud</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>cloud-provider-payment8001</artifactId><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><!--SpringBoot通用依赖模块--><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><!--SpringBoot集成druid连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId></dependency><!--mybatis和springboot整合--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId></dependency><!--Mysql数据库驱动8 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!--hutool--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId></dependency><!-- fastjson2 --><dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2</artifactId></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.28</version><scope>provided</scope></dependency><!--test--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- knife4j API文档平台 --><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId><version>4.4.0</version></dependency><!--persistence--><dependency><groupId>javax.persistence</groupId><artifactId>persistence-api</artifactId></dependency><!--通用Mapper4--><dependency><groupId>tk.mybatis</groupId><artifactId>mapper</artifactId></dependency><!-- Swagger3 调用方式 http://你的主机IP地址:5555/swagger-ui/index.html --><!-- <dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-starter-webmvc-ui</artifactId></dependency>--><dependency><groupId>com.xiaozhi.cloud</groupId><artifactId>cloud-api-commons</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><!--consul--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-consul-discovery</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.4.RELEASE</version><configuration><fork>true</fork><addResources>true</addResources></configuration></plugin></plugins></build>
</project>
- ②. yaml文件
server:port: 8001# ==========applicationName + druid-mysql8 driver===================
spring:application:name: cloud-payment-servicedatasource:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/db2024?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=trueusername: rootpassword: root# ========================mybatis===================
mybatis:mapper-locations: classpath:mapper/*.xmltype-aliases-package: com.xiaozhi.cloud.entitiesconfiguration:map-underscore-to-camel-case: truespringdoc:swagger-ui:path: /swagger-ui.htmltags-sorter: alphaoperations-sorter: alphaapi-docs:path: /v3/api-docsgroup-configs:- group: 'cloud-provider-payment8001'paths-to-match: '/**'#生成文档所需的扫包路径,一般为启动类目录packages-to-scan: com.xiaozhi.cloud.controller
#knife4j配置
knife4j:# 是否开启Knife4j增强模式,无需添加@EnableKnife4j注解enable: true#开启生产环境屏蔽production: false#是否启用登录认证basic:enable: trueusername: adminpassword: 123456setting:language: zh_cn# 是否开启界面中对某接口的版本控制,如果开启,后端变化后Ui界面会存在小蓝点enable-version: false# 是否显示界面中SwaggerModel功能enable-swagger-models: true# 重命名SwaggerModel名称,默认swagger-model-name: 实体类列表
- ③. 主启动类
@MapperScan("com.xiaozhi.cloud.mapper")
@SpringBootApplication
@EnableDiscoveryClient
public class Main8001 {public static void main(String[] args) {SpringApplication.run(Main8001.class,args);}
}
- ④. entities类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PayDTO implements Serializable
{private Integer id;//支付流水号private String payNo;//订单流水号private String orderNo;//用户账号IDprivate Integer userId;//交易金额private BigDecimal amount;
}
@Table(name = "t_pay")
@Data
public class Pay {@Id@GeneratedValue(generator = "JDBC")private Integer id;/*** 支付流水号*/@Column(name = "pay_no")@NotNull(message = "支付流水号不能为空")private String payNo;/*** 订单流水号*/@Column(name = "order_no")private String orderNo;/*** 用户账号ID*/@Column(name = "user_id")private Integer userId;/*** 交易金额*/private BigDecimal amount;/*** 删除标志,默认0不删除,1删除*/private Byte deleted;/*** 创建时间*/@Column(name = "create_time")private Date createTime;/*** 更新时间*/@Column(name = "update_time")private Date updateTime;
}
- ⑤. controller类
@RestController
/*@Tag(tags = "支付微服务模块", description = "支付CRUD")*/
@Tag(name = "支付微服务模块", description = "支付CRUD")
@Slf4j
public class PayController {@Resourceprivate PayService payService;@PostMapping(value = "/pay/add")@Operation(summary = "新增",description = "(新增支付流水方法,json串做参数)")public ResultData<String> addPay(@RequestBody Pay pay){System.out.println(pay.toString());int i = payService.add(pay);return ResultData.success("成功插入记录,返回值:"+i);}@DeleteMapping(value = "/pay/del/{id}")@Operation(summary = "删除(删除支付流水方法)")// @ApiOperation(value = "删除(删除支付流水方法)")public ResultData<Integer> detelePay(@PathVariable("id") Integer id){int i = payService.delete(id);return ResultData.success(i);}@PutMapping(value = "/pay/update")// @ApiOperation(value = "修改(修改支付流水方法)")private ResultData<String> updatePay(@RequestBody PayDTO payDTO){Pay pay = new Pay();BeanUtils.copyProperties(payDTO,pay);int i = payService.update(pay);return ResultData.success("成功修改记录,返回值:"+i);}@GetMapping(value = "/pay/get/{id}")
// @ApiImplicitParam(name = "id", value = "按照ID查流水(查询支付流水方法id)", required=true,
// dataType = "Integer")public ResultData<Pay> getById(@PathVariable("id") Integer id){Pay pay = payService.getById(id);//暂停62秒,测试出feign的默认超时时间//try { TimeUnit.SECONDS.sleep(62); }catch (Exception e) {e.printStackTrace();}return ResultData.success(pay);}@GetMapping("/pay/all")
// @ApiOperation(value = "查询支付的所有信息(查询支付的所有信息方法)")public ResultData<List<Pay>> getAll(){int i = 10 /0;List<Pay> all = payService.getAll();return ResultData.success(all);}
}
-
⑥. 进入网址进行测试:http://localhost:8001/doc.html
-
⑦. 时间格式问题、时间日志格式的统一和定制情况?
-
⑧. Java如何设计API接口实现统一格式返回?
@Data
@Accessors(chain = true)
public class ResultData<T> {private String code;/** 结果状态 ,具体状态码参见枚举类ReturnCodeEnum.java*/private String message;private T data;private long timestamp ;public ResultData (){this.timestamp = System.currentTimeMillis();}public static <T> ResultData<T> success(T data) {ResultData<T> resultData = new ResultData<>();resultData.setCode(ReturnCodeEnum.RC200.getCode());resultData.setMessage(ReturnCodeEnum.RC200.getMessage());resultData.setData(data);return resultData;}public static <T> ResultData<T> fail(String code, String message) {ResultData<T> resultData = new ResultData<>();resultData.setCode(code);resultData.setMessage(message);return resultData;}
}
@Getter
public enum ReturnCodeEnum
{/**操作失败**/RC999("999","操作XXX失败"),/**操作成功**/RC200("200","success");/**自定义状态码**/private final String code;/**自定义描述**/private final String message;ReturnCodeEnum(String code, String message){this.code = code;this.message = message;}//遍历枚举V1public static ReturnCodeEnum getReturnCodeEnum(String code){for (ReturnCodeEnum element : ReturnCodeEnum.values()) {if(element.getCode().equalsIgnoreCase(code)){return element;}}return null;}//遍历枚举V2public static ReturnCodeEnum getReturnCodeEnumV2(String code){return Arrays.stream(ReturnCodeEnum.values()).filter(x -> x.getCode().equalsIgnoreCase(code)).findFirst().orElse(null);}// public static void main(String[] args)
// {
// System.out.println(getReturnCodeEnumV2("200"));
// System.out.println(getReturnCodeEnumV2("200").getCode());
// System.out.println(getReturnCodeEnumV2("200").getMessage());
// }
}
- ⑨. 全局异常接入返回的标准格式
@GetMapping(value = "/pay/get/{id}")@Operation(summary = "按照ID查流水",description = "查询支付流水方法")public ResultData<Pay> getById(@PathVariable("id") Integer id){if(id == -4) throw new RuntimeException("id不能为负数");Pay pay = payService.getById(id);return ResultData.success(pay);}
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler
{/*** 默认全局异常处理。* @param e the e* @return ResultData*/@ExceptionHandler(RuntimeException.class)@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)public ResultData<String> exception(Exception e) {System.out.println("----come in GlobalExceptionHandler");log.error("全局异常信息exception:{}", e.getMessage(), e);return ResultData.fail(ReturnCodeEnum.RC500.getCode(),e.getMessage());}
}
⑥. 订单微服务 - consumer80
-
①. Restemplate各个调用方法如下链接所示
-
②. 建cloud-consumer-order服务,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>mscloudV5</artifactId><groupId>com.xiaozhi.cloud</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>cloud-consumer-order80</artifactId><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><!--loadbalancer-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-loadbalancer</artifactId>-->
<!-- </dependency>--><!--SpringCloud consul discovery -->
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-consul-discovery</artifactId>-->
<!-- <exclusions>-->
<!-- <exclusion>-->
<!-- <groupId>commons-logging</groupId>-->
<!-- <artifactId>commons-logging</artifactId>-->
<!-- </exclusion>-->
<!-- </exclusions>-->
<!-- </dependency>--><!-- 引入自己定义的api通用包 --><dependency><groupId>com.xiaozhi.cloud</groupId><artifactId>cloud-api-commons</artifactId><version>1.0-SNAPSHOT</version></dependency><!--web + actuator--><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><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!--hutool-all--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId></dependency><!--fastjson2--><dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2</artifactId></dependency><!-- knife4j API文档平台 --><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId><version>4.4.0</version></dependency><!-- <dependency>--><!-- <groupId>com.hhf.cloud</groupId>--><!-- <artifactId>cloud-provider-payment8001</artifactId>--><!-- <version>1.0-SNAPSHOT</version>--><!-- <scope>compile</scope>--><!-- </dependency>--><!--consul--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-consul-discovery</artifactId></dependency><!--SpringCloud consul config--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-consul-config</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.4.RELEASE</version><configuration><fork>true</fork><addResources>true</addResources></configuration></plugin></plugins></build>
</project>
- ③. yaml文件如下
spring:#配置服务名application:name: cloud-consumer-order
server:port: 80
spring:profiles:active: prod
springdoc:swagger-ui:path: /swagger-ui.htmltags-sorter: alphaoperations-sorter: alphaapi-docs:path: /v3/api-docsgroup-configs:- group: 'cloud-consumer-order80'paths-to-match: '/**'#生成文档所需的扫包路径,一般为启动类目录packages-to-scan: com.xiaozhi.cloud.controller
#knife4j配置
knife4j:# 是否开启Knife4j增强模式,无需添加@EnableKnife4j注解enable: true#开启生产环境屏蔽production: false#是否启用登录认证basic:enable: trueusername: adminpassword: 123456setting:language: zh_cn# 是否开启界面中对某接口的版本控制,如果开启,后端变化后Ui界面会存在小蓝点enable-version: false# 是否显示界面中SwaggerModel功能enable-swagger-models: true# 重命名SwaggerModel名称,默认swagger-model-name: 实体类列表
- ④. 主启动类
//@EnableDiscoveryClient //该注解用于向使用consul为注册中心时注册服务
//@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class})
@SpringBootApplication
//@RefreshScope
public class Main80 {public static void main(String[] args) {SpringApplication.run(Main80.class,args);}
}
- ⑤. controller层
@RestController
public class OrderController {public static final String PaymentSrv_URL = "http://localhost:8001";//先写死,硬编码// public static final String PaymentSrv_URL = "http://cloud-payment-service";//服务注册中心上的微服务名称@Autowiredprivate RestTemplate restTemplate;/*** 一般情况下,通过浏览器的地址栏输入url,发送的只能是get请求* 我们底层调用的是post方法,模拟消费者发送get请求,客户端消费者* 参数可以不添加@RequestBody** @param payDTO* @return*/@GetMapping("/consumer/pay/add")public ResultData addOrder(PayDTO payDTO) {return restTemplate.postForObject(PaymentSrv_URL + "/pay/add", payDTO, ResultData.class);}// 删除+修改操作作为家庭作业,O(∩_∩)O。。。。。。。@GetMapping("/consumer/pay/get/{id}")public ResultData getPayInfo(@PathVariable("id") Integer id) {return restTemplate.getForObject(PaymentSrv_URL + "/pay/get/{id}", ResultData.class, id);// return restTemplate.getForObject(PaymentSrv_URL + "/pay/get/{id}" + id, ResultData.class, id);}@GetMapping(value = "/consumer/pay/get/info")private String getInfoByConsul() {return restTemplate.getForObject(PaymentSrv_URL + "/pay/get/info", String.class);}
}
- ⑥. 到目前为止,我们的工程架构如下所示
⑦. 热部署Devtools(开发阶段)
- ①. adding devtools to your project
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency>
- ②. adding plugin to your pom.xml(添加聚合父类总工程的pom.xml)
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><fork>true</fork><addResources>true</addResources></configuration></plugin></plugins></build>
- ③. Enabling automatic build(开启自动编译的选项)
- ④. Update the value of(更新值)
Ctrl+Shift+A打开全局搜索搜registry
- ⑤. 重启Idea
⑧. 测试Run DashBord
-
①. 运用spring cloud框架基于spring boot构建微服务,一般需要启动多个应用程序,在idea开发工具中,多个同时启动的应用需要在RunDashboard运行仪表盘中可以更好的管理,但有时候idea中的RunDashboard窗口没有显示出来,也找不到直接的开启钮;idea中打开Run Dashboard的方法如下:
view > Tool Windows > Run Dashboard -
②. 在workspace.xml中添加如下配置
<component name="RunDashboard">
<option name="configurationTypes"><set><option value="SpringBootApplicationConfigurationType"/></set>
</option>
<option name="ruleStates"><list><RuleState><option name="name" value="ConfigurationTypeDashboardGroupingRule"/></RuleState><RuleState><option name="name" value="StatusDashboardGroupingRule"/></RuleState></list>
</option>
</component>