本项目的笔记和资料的Download,请点击这一句话自行获取。

day01-springboot(理论篇) ;day01-springboot(实践篇)

day02-springcloud(理论篇一)  ;day02-springcloud(理论篇二)  ;day02-springcloud(理论篇三) ;day02-springcloud(理论篇四) ;

day03-springcloud(Hystix,Feign)  ;day03-springcloud(Zuul网关)

day04-项目搭建(一) ;day04-项目搭建(二)day04-ES6语法入门

day05-Vue入门学习

day06-了解vue-router和webpack的使用

14 微服务电商【黑马乐优商城】:day04-项目搭建(二)


0.学习目标

  • 了解乐优商城项目结构
  • 能独立搭建项目基本框架
  • 能参考使用ES6的新语法

3.4.创建父工程

创建统一的父工程:leyou,用来管理依赖及其版本,注意是创建project,而不是module

填写项目信息:

然后将pom文件修改成我这个样子:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <!--
  7. 子模块天生继承父工程,可以使用父工程所有资源。
  8. 子模块之间天生是没有任何关系的。
  9.  
  10. 父子工程直接不用建立关系,继承关系是先天的,不需要手动建立。
  11. 平级直接的引用叫依赖,依赖不是先天的,依赖是需要后天建立的。
  12. -->
  13. <groupId>com.leyou.parent</groupId>
  14. <artifactId>leyou</artifactId>
  15. <version>1.0-SNAPSHOT</version>
  16. <packaging>pom</packaging>
  17.  
  18. <parent>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-parent</artifactId>
  21. <version>2.0.8.RELEASE</version>
  22. <relativePath/> <!-- lookup parent from repository -->
  23. </parent>
  24.  
  25. <properties>
  26. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  27. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  28. <java.version>1.8</java.version>
  29. <spring-cloud.version>Finchley.SR4</spring-cloud.version>
  30. <mybatis.starter.version>1.3.5</mybatis.starter.version>
  31. <mapper.starter.version>2.1.15</mapper.starter.version>
  32. <pageHelper.starter.version>1.2.12</pageHelper.starter.version>
  33. <druid.starter.version>1.1.10</druid.starter.version>
  34. <mysql.version>5.1.45</mysql.version>
  35. <leyou.latest.version>1.0.0-SNAPSHOT</leyou.latest.version>
  36. <fastDFS.client.version>1.26.1-RELEASE</fastDFS.client.version>
  37. </properties>
  38.  
  39. <dependencyManagement>
  40. <dependencies>
  41. <!-- springCloud -->
  42. <dependency>
  43. <groupId>org.springframework.cloud</groupId>
  44. <artifactId>spring-cloud-dependencies</artifactId>
  45. <version>${spring-cloud.version}</version>
  46. <type>pom</type>
  47. <scope>import</scope>
  48. </dependency>
  49. <!-- mybatis启动器 -->
  50. <dependency>
  51. <groupId>org.mybatis.spring.boot</groupId>
  52. <artifactId>mybatis-spring-boot-starter</artifactId>
  53. <version>${mybatis.starter.version}</version>
  54. </dependency>
  55. <!-- 通用Mapper启动器 -->
  56. <dependency>
  57. <groupId>tk.mybatis</groupId>
  58. <artifactId>mapper-spring-boot-starter</artifactId>
  59. <version>${mapper.starter.version}</version>
  60. </dependency>
  61. <!-- 分页助手启动器 -->
  62. <dependency>
  63. <groupId>com.github.pagehelper</groupId>
  64. <artifactId>pagehelper-spring-boot-starter</artifactId>
  65. <version>${pageHelper.starter.version}</version>
  66. </dependency>
  67. <!-- mysql驱动 -->
  68. <dependency>
  69. <groupId>mysql</groupId>
  70. <artifactId>mysql-connector-java</artifactId>
  71. <version>${mysql.version}</version>
  72. </dependency>
  73. <!--FastDFS客户端-->
  74. <dependency>
  75. <groupId>com.github.tobato</groupId>
  76. <artifactId>fastdfs-client</artifactId>
  77. <version>${fastDFS.client.version}</version>
  78. </dependency>
  79. </dependencies>
  80. </dependencyManagement>
  81.  
  82. <build>
  83. <plugins>
  84. <plugin>
  85. <groupId>org.springframework.boot</groupId>
  86. <artifactId>spring-boot-maven-plugin</artifactId>
  87. </plugin>
  88. </plugins>
  89. </build>
  90. </project>

在父工程中引入了SpringCloud等,很多以后需要用到的依赖,以后创建的子工程就不需要自己引入了。

可以删除src目录,工程结构如下:

3.5.创建EurekaServer

3.5.1.创建工程

我们的注册中心,起名为:leyou-registry

选择新建module:

然后填写项目坐标,我们的项目名称为 leyou-registry

选择安装目录,因为是聚合项目,目录应该是在父工程leyou的下面。

3.5.2.添加依赖

添加EurekaServer的依赖:

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
  5. </dependency>
  6.  
  7. </dependencies>

3.5.3.编写启动类

com.leyou.LeyouRegistryApplication

  1. @SpringBootApplication
  2. @EnableEurekaServer
  3. public class LeyouRegistryApplication {
  4.  
  5. public static void main(String[] args) {
  6. SpringApplication.run(LeyouRegistryApplication.class, args);
  7. }
  8. }

3.5.4.配置文件

  1. #tomcat服务器端口
  2. server:
  3. port: 10086
  4. #服务名称
  5. spring:
  6. application:
  7. name: leyou-registry
  8. #注册中心
  9. eureka:
  10. client:
  11. service-url:
  12. defaultZone: http://127.0.0.1:${server.port}/eureka
  13. register-with-eureka: false # 把自己注册到eureka服务列表
  14. fetch-registry: false # 拉取eureka服务信息
  15. server:
  16. enable-self-preservation: false # 关闭自我保护
  17. eviction-interval-timer-in-ms: 5000 # 每隔5秒钟,进行一次服务列表的清理

3.6.创建Zuul网关

3.6.1.创建工程

与上面类似,选择maven方式创建Module,然后填写项目名称,我们命名为:leyou-gateway

3.6.2.添加依赖

这里我们需要添加Zuul和EurekaClient的依赖:

  1. <dependencies>
  2. <!--Zuul网关的依赖启动器-->
  3. <dependency>
  4. <groupId>org.springframework.cloud</groupId>
  5. <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
  6. </dependency>
  7. <!--eureka-client的依赖-->
  8. <dependency>
  9. <groupId>org.springframework.cloud</groupId>
  10. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  11. </dependency>
  12. <!-- springboot提供微服务检测接口,默认对外提供几个接口 -->
  13. <dependency>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-actuator</artifactId>
  16. </dependency>
  17. </dependencies>

3.6.3.编写启动类

com.leyou.LeyouGatewayApplication

  1. @SpringBootApplication
  2. @EnableDiscoveryClient
  3. @EnableZuulProxy
  4. public class LeyouGatewayApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(LeyouGatewayApplication.class, args);
  7. }
  8. }

3.6.4.配置文件

  1. #tomcat服务端口
  2. server:
  3. port: 10010
  4. #服务名称
  5. spring:
  6. application:
  7. name: leyou-gateway
  8.  
  9. #注册中心的客户端配置
  10. eureka:
  11. client:
  12. service-url:
  13. defaultZone: http://127.0.0.1:10086/eureka
  14. registry-fetch-interval-seconds: 5 #拉取eureka服务信息的时间间隔
  15. #zuul网关的配置项
  16. zuul:
  17. prefix: /api # 添加路由前缀
  18. routes:
  19. item-service: /item/** # 商品微服务的映射路径
  20.  
  21. #熔断器的配置
  22. hystrix:
  23. command:
  24. default:
  25. execution:
  26. isolation:
  27. thread:
  28. timeoutInMilliseconds: 5000 # 熔断超时时长:5000ms
  29.  
  30. #负载均衡
  31. ribbon:
  32. ConnectTimeout: 1000 # ribbon链接超时时长
  33. ReadTimeout: 3500 # ribbon读取超时时长
  34. MaxAutoRetries: 0 # 当前服务重试次数
  35. MaxAutoRetriesNextServer: 0 # 切换服务重试次数

3.6.5.项目结构

目前,leyou下有两个子模块:

  • leyou-registry:服务的注册中心(EurekaServer)
  • leyou-gateway:服务网关(Zuul)

截止到这里,我们已经把基础服务搭建完毕,为了便于开发,统一配置中心(ConfigServer)我们留待以后添加。


3.7.创建商品微服务

既然是一个全品类的电商购物平台,那么核心自然就是商品。因此我们要搭建的第一个服务,就是商品微服务。其中会包含对于商品相关的一系列内容的管理,包括:

  • 商品分类管理
  • 品牌管理
  • 商品规格参数管理
  • 商品管理
  • 库存管理

3.7.1.微服务的结构

因为与商品的品类相关,我们的工程命名为leyou-item.

需要注意的是,我们的leyou-item是一个微服务,那么将来肯定会有其它系统需要来调用服务中提供的接口,获取的接口数据,也需要对应的实体类来封装,因此肯定也会使用到接口中关联的实体类。

因此这里我们需要使用聚合工程,将要提供的接口及相关实体类放到独立子工程中,以后别人引用的时候,只需要知道坐标即可。

我们会在leyou-item中创建两个子工程:

  • leyou-item-interface:主要是对外暴露的接口及相关实体类
  • leyou-item-service:所有业务逻辑及内部使用接口

调用关系如图所示:

3.7.2.leyou-item

依然是使用maven构建:

因为是聚合工程,所以把项目打包方式设置为pom

  1. <!-- 因为是聚合工程,所以打包方式为pom -->
  2. <packaging>pom</packaging>

3.7.3.leyou-item-interface

在leyou-item工程上点击右键,选择new --> module:

依然是使用maven构建,注意父工程是leyou-item:

注意:目录结构,保存到leyou-item下的leyou-item-interface目录中。

3.7.4.leyou-item-service

leyou-item-interface类似,我们选择在leyou-item上右键,新建module,然后填写项目信息:

3.7.5.整个微服务结构

如图所示:

我们打开leyou-item的pom查看,会发现leyou-item-interface和leyou-item-service都已经成为module了:

可以删除leyou-item工程的src目录

3.7.6.添加依赖

接下来我们给leyou-item-service中添加依赖:

思考一下我们需要什么?

  • Eureka客户端
  • web启动器
  • mybatis启动器
  • 通用mapper启动器
  • 分页助手启动器
  • 连接池,我们用默认的Hykira
  • mysql驱动
  • 千万不能忘了,我们自己也需要ly-item-interface中的实体类

这些依赖,我们在顶级父工程:leyou中已经添加好了。所以直接引入即可:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>leyou-item</artifactId>
  7. <groupId>com.leyou.item</groupId>
  8. <version>1.0.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11.  
  12. <groupId>com.leyou.item</groupId>
  13. <artifactId>leyou-item-service</artifactId>
  14.  
  15. <dependencies>
  16. <!-- web启动器 -->
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-web</artifactId>
  20. </dependency>
  21. <!-- eureka客户端 -->
  22. <dependency>
  23. <groupId>org.springframework.cloud</groupId>
  24. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  25. </dependency>
  26. <!--mybatis的启动器-->
  27. <dependency>
  28. <groupId>org.mybatis.spring.boot</groupId>
  29. <artifactId>mybatis-spring-boot-starter</artifactId>
  30. </dependency>
  31. <!-- 通用mapper启动器 -->
  32. <dependency>
  33. <groupId>tk.mybatis</groupId>
  34. <artifactId>mapper-spring-boot-starter</artifactId>
  35. </dependency>
  36. <!--分页助手启动器-->
  37. <dependency>
  38. <groupId>com.github.pagehelper</groupId>
  39. <artifactId>pagehelper-spring-boot-starter</artifactId>
  40. </dependency>
  41. <!-- mysql驱动 -->
  42. <dependency>
  43. <groupId>mysql</groupId>
  44. <artifactId>mysql-connector-java</artifactId>
  45. </dependency>
  46. <!--平级的模块之间调用要手动导依赖坐标-->
  47. <dependency>
  48. <groupId>com.leyou.item</groupId>
  49. <artifactId>leyou-item-interface</artifactId>
  50. <version>1.0.0-SNAPSHOT</version>
  51. </dependency>
  52. <!-- springboot检测服务启动器 -->
  53. <dependency>
  54. <groupId>org.springframework.boot</groupId>
  55. <artifactId>spring-boot-starter-actuator</artifactId>
  56. </dependency>
  57. </dependencies>
  58.  
  59. </project>

leyou-item-interface中需要什么我们暂时不清楚,所以先不管。以后需要什么依赖,再引入。

通用mapper的启动器内部自带引用 mybatis和jdbc的启动器。

3.7.7.编写启动和配置

在整个leyou-item工程中,只有leyou-item-service是需要启动的。因此在其中编写启动类即可:

  1. @SpringBootApplication
  2. @EnableDiscoveryClient
  3. public class LeyouItemServiceApplication {
  4.  
  5. public static void main(String[] args) {
  6. SpringApplication.run(LeyouItemServiceApplication.class, args);
  7. }
  8. }

然后是全局属性application.yml文件:

  1. #tomcat服务端口
  2. server:
  3. port:
  4. #服务名称
  5. spring:
  6. application:
  7. name: item-service
  8. datasource:
  9. url: jdbc:mysql://localhost:3306/leyou
  10. username: root
  11. password: root
  12. hikari:
  13. max-lifetime: # 一个连接的生命时长(毫秒),超时而且没被使用则被释放(retired),缺省:30分钟,建议设置比数据库超时时长少30秒,参考MySQL wait_timeout参数(show variables like '%timeout%';)
  14. maximum-pool-size: # 连接池中允许的最大连接数。缺省值:;推荐的公式:((core_count * ) + effective_spindle_count)
  15. driver-class-name: com.mysql.jdbc.Driver
  16.  
  17. #注册中心
  18. eureka:
  19. client:
  20. service-url:
  21. defaultZone: http://127.0.0.1:10086/eureka
  22. #register-with-eureka: false # 把自己注册到eureka服务列表
  23. #fetch-registry: false # 拉取eureka服务信息
  24. instance:
  25. prefer-ip-addresss: true
  26. ip-address: 127.0.0.1
  27. lease-renewal-interval-in-seconds: # 5秒钟发送一次心跳
  28. lease-expiration-duration-in-seconds: # 10秒不发送就过期

3.8.添加商品微服务的路由规则

既然商品微服务已经创建,接下来肯定要添加路由规则到Zuul中,我们不使用默认的路由规则。

使用如下代码到leyou-gateway工程的application.yml配置文件:

  1. zuul:
  2. prefix: /api # 路由路径前缀
  3. routes:
  4. item-service: /item/** # 商品微服务的映射路径

3.9.启动测试

我们按顺序分别启动:leyou-registry,leyou-gateway,leyou-item-service

查看Eureka面板:

3.10.测试路由规则

为了测试路由规则是否畅通,我们是不是需要在item-service中编写一个controller接口呢?

其实不需要,SpringBoot提供了一个依赖:actuator

只要我们添加了actuator的依赖,它就会为我们生成一系列的访问接口:

  • /info
  • /health
  • /refresh

添加依赖:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-actuator</artifactId>
  4. </dependency>

重启后访问Eureka控制台:

鼠标悬停在item-service上,会显示一个地址:

这就是actuator提供的接口,我们点击访问:

因为我们没有添加信息,所以是一个空的json,但是可以肯定的是:我们能够访问到item-service了。

接下来我们通过路由访问试试,根据路由规则,我们需要访问的地址是:

http://127.0.0.1:10010/api/item/actuator/info

3.11.通用工具模块

有些工具或通用的约定内容,我们希望各个服务共享,因此需要创建一个工具模块:leyou-common

右键leyou工程,使用maven来构建module:

工程结构:

目前还不需要自己写工具类,我们从课前资料里直接导入即可。

选中java目录,新建一个package:com.leyou.common.utils

把资料里的4个工具类copy到刚才新建的utils目录里。

在leyou-common模块的pom.xml添加依赖坐标:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>leyou</artifactId>
  7. <groupId>com.leyou.parent</groupId>
  8. <version>1.0.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11.  
  12. <groupId>com.leyou.common</groupId>
  13. <artifactId>leyou-common</artifactId>
  14.  
  15. <dependencies>
  16. <dependency> <!-- log日志启动器 -->
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-logging</artifactId>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.apache.tomcat.embed</groupId>
  22. <artifactId>tomcat-embed-core</artifactId>
  23. <scope>provided</scope>
  24. </dependency>
  25. <dependency><!--springMVC的JSON反序列化把{}字符串转成对象-->
  26. <groupId>com.fasterxml.jackson.core</groupId>
  27. <artifactId>jackson-databind</artifactId>
  28. <version>2.9.9.3</version>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.jetbrains</groupId>
  32. <artifactId>annotations</artifactId>
  33. <version>13.0</version>
  34. <scope>compile</scope>
  35. </dependency>
  36. </dependencies>
  37.  
  38. </project>

jackson的工具类JsonUtils的使用


5.通用异常处理

在上图interface的java目录下新建一个实体类:

com.leyou.item.pojo.Item

  1. package com.leyou.item.pojo;
  2.  
  3. import lombok.Data;
  4.  
  5. @Data //字节码阶段自动生成get/set/toString方法
  6. public class Item {
  7. private Integer id;
  8. private String name;
  9. private Long price;
  10. }

在商品服务模块下新建一个类:

com.leyou.item.service.ItemService

  1. @Service
  2. public class ItemService {
  3. public Item saveItem(Item item){
  4. //模拟商品新增
  5. int id = new Random().nextInt(100); //产生随机数0~99
  6. item.setId(id);
  7. return item;
  8. }
  9. }

REST规范的URI定义

HTTP协议响应状态码

Insomnia.Setup.7.0.1.exe 下载该软件作为调试REST工具

https://www.insomnia.rest/
Debug APIs like a human, not a robot
Finally, a REST client you'll love


新建一个web层的Controller类

com.leyou.item.web.ItemController

  1. @RestController
  2. @RequestMapping("item")
  3. public class ItemController {
  4. @Autowired
  5. private ItemService itemService;
  6.  
  7. @PostMapping
  8. public ResponseEntity<Item> saveItem(Item item){
  9. //校验价格。如果价格为空,则抛出异常,返回400状态码
  10. if(item.getPrice() == null){
  11. return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
  12. }
  13. Item result = itemService.saveItem(item);
  14. return ResponseEntity.status(HttpStatus.CREATED).body(result);
  15. }
  16. }

模拟客户端浏览器提交POST请求,需要使用一个REST Client作为测试工具。

https://github.com/wisdom-projects/rest-client

特点是使用方便,因为他只是一个jar包,双击执行(当然前提是你电脑上安装并配置环境变量jdk1.8版本)

5.2.3 使用springMVC提供的统一异常拦截器

我们先修改controller的代码,把异常抛出:

  1. @RestController
  2. @RequestMapping("item")
  3. public class ItemController {
  4. @Autowired
  5. private ItemService itemService;
  6.  
  7. @PostMapping
  8. public ResponseEntity<Item> saveItem(Item item){
  9. //校验价格。如果价格为空,则抛出异常,返回400状态码
  10. if(item.getPrice() == null){
  11. //return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
  12. throw new RuntimeException("价格不能为空");
  13. }
  14. Item result = itemService.saveItem(item);
  15. return ResponseEntity.status(HttpStatus.CREATED).body(result);
  16. }
  17. }

然后在leyou-common工程下的pom.xml添加SpringMVC的依赖坐标

  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-webmvc</artifactId>
  4. </dependency>

com.leyou.common.advice.CommonExceptionHandler

也可以叫作BasicExceptionHandler

  1. @ControllerAdvice //默认拦截所有加了@Controller注解的类
  2. public class CommonExceptionHandler {
  3.  
  4. @ExceptionHandler(RuntimeException.class)
  5. public ResponseEntity<String> handleException(RuntimeException e){
  6. return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
  7.  
  8. }
  9. }

leyou-Item-service 的pom.xml添加引入leyou-common模块的依赖坐标:

  1. <dependency>
  2. <groupId>com.leyou.common</groupId>
  3. <artifactId>leyou-common</artifactId>
  4. <version>1.0.0-SNAPSHOT</version>
  5. </dependency>

5.2.4 自定义异常

返回至ly-common子模块,新建一个package

com.leyou.common.enums

新建一个枚举类(有固定实例化个数的Class)

  1. package com.leyou.common.enums;
  2.  
  3. import lombok.AllArgsConstructor;
  4. import lombok.Getter;
  5. import lombok.NoArgsConstructor;
  6.  
  7. @Getter
  8. @NoArgsConstructor
  9. @AllArgsConstructor
  10. public enum ExceptionEnum {
  11.  
  12. PRICE_CANNOT_BE_NULL(400,"价格不能为空!")
  13. ;
  14. private int code;
  15. private String msg;
  16.  
  17. }

创建自定义异常类继承于 RuntimeException

  1. package com.leyou.common.exception;
  2.  
  3. import com.leyou.common.enums.ExceptionEnum;
  4. import lombok.AllArgsConstructor;
  5. import lombok.Getter;
  6. import lombok.NoArgsConstructor;
  7.  
  8. @NoArgsConstructor
  9. @AllArgsConstructor
  10. @Getter
  11. public class LyException extends RuntimeException {
  12. private ExceptionEnum exceptionEnum;
  13. //1.自定义异常先继承 RuntimeException
  14. //2.把枚举类作为私有的成员变量
  15. //3.提供Getter方法
  16. //4.提供空参构造器和全参构造器
  17. }

创建一个异常结果对象类,用来封装异常属性信息。

com.leyou.common.vo.ExceptionResult

  1. package com.leyou.common.vo;
  2.  
  3. import com.leyou.common.enums.ExceptionEnum;
  4. import lombok.Data;
  5.  
  6. @Data
  7. public class ExceptionResult {
  8. private int status;
  9. private String message;
  10. private Long timestamp;
  11.  
  12. public ExceptionResult(ExceptionEnum em){
  13. this.status = em.getCode();
  14. this.message = em.getMsg();
  15. this.timestamp = System.currentTimeMillis();
  16. }
  17.  
  18. }

最后返回到com.leyou.common.advice.CommonExceptionHandler 修改后的代码如下:

  1. package com.leyou.common.advice;
  2.  
  3. import com.leyou.common.enums.ExceptionEnum;
  4. import com.leyou.common.exception.LyException;
  5. import com.leyou.common.vo.ExceptionResult;
  6. import org.springframework.http.ResponseEntity;
  7. import org.springframework.web.bind.annotation.ControllerAdvice;
  8. import org.springframework.web.bind.annotation.ExceptionHandler;
  9.  
  10. @ControllerAdvice //默认拦截所有加了@Controller注解的类
  11. public class CommonExceptionHandler {
  12.  
  13. @ExceptionHandler(LyException.class)
  14. public ResponseEntity<ExceptionResult> handleException(LyException e){
  15. //从被拦截的异常中取出枚举的成员变量
  16. ExceptionEnum em = e.getExceptionEnum();
  17. return ResponseEntity.status(em.getCode())
  18. .body(new ExceptionResult(e.getExceptionEnum()));
  19.  
  20. }
  21. }

com.leyou.item.web.ItemController

  1. @RestController
  2. @RequestMapping("item")
  3. public class ItemController {
  4. @Autowired
  5. private ItemService itemService;
  6.  
  7. @PostMapping
  8. public ResponseEntity<Item> saveItem(Item item){
  9. //校验价格。如果价格为空,则抛出异常,返回400状态码
  10. if(item.getPrice() == null){
  11. //return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
  12. //throw new RuntimeException("价格不能为空");
  13. throw new LyException(ExceptionEnum.PRICE_CANNOT_BE_NULL);
  14. }
  15. Item result = itemService.saveItem(item);
  16. return ResponseEntity.status(HttpStatus.CREATED).body(result);
  17. }
  18. }

最后不要忘记在leyou-common工具类子模块的pom.xml添加以下打包插件的配置:

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-maven-plugin</artifactId>
  6. <executions><!--是为了解决Unable to find main class的问题-->
  7. <execution>
  8. <phase>none</phase>
  9. </execution>
  10. </executions>
  11. <configuration><!--是为了解决install找不到依赖包的问题-->
  12. <classifier>execute</classifier>
  13. </configuration>
  14. </plugin>
  15. </plugins>
  16. </build>

自定义异常处理返回de封装对象 HTTP RESTClient

=============================================

参考资料:

RESTClient 使用

Wisdom REST Client 简介

spring-boot-maven-plugin 插件 install时报错 程序包不存在以及找不到类的情况

end

14 微服务电商【黑马乐优商城】:day04-项目搭建(二)的更多相关文章

  1. 14 微服务电商【黑马乐优商城】:day01-springboot(理论篇)

    本项目的笔记和资料的Download,请点击这一句话自行获取. day01-springboot(理论篇) :day01-springboot(实践篇) :day01-springboot(Thyme ...

  2. 14 微服务电商【黑马乐优商城】:day06-使用nginx反向代理并掌握cors解决跨域

    本项目的笔记和资料的Download,请点击这一句话自行获取. day01-springboot(理论篇) :day01-springboot(实践篇) day02-springcloud(理论篇一) ...

  3. 14 微服务电商【黑马乐优商城】:day06-了解vue-router和webpack的使用

    本项目的笔记和资料的Download,请点击这一句话自行获取. day01-springboot(理论篇) :day01-springboot(实践篇) day02-springcloud(理论篇一) ...

  4. 14 微服务电商【黑马乐优商城】:day04-ES6语法入门

    day01-springboot(理论篇) :day01-springboot(实践篇) day02-springcloud(理论篇一)  :day02-springcloud(理论篇二)  :day ...

  5. 14 微服务电商【黑马乐优商城】:day04-项目搭建(一)

    本项目的笔记和资料的Download,请点击这一句话自行获取. day01-springboot(理论篇) :day01-springboot(实践篇) day02-springcloud(理论篇一) ...

  6. 14 微服务电商【黑马乐优商城】:day03-springcloud(Zuul网关)

    本项目的笔记和资料的Download,请点击这一句话自行获取. day01-springboot(理论篇) :day01-springboot(实践篇) day02-springcloud(理论篇一) ...

  7. 14 微服务电商【黑马乐优商城】:day03-springcloud(Hystix,Feign)

    本项目的笔记和资料的Download,请点击这一句话自行获取. day01-springboot(理论篇) :day01-springboot(实践篇) day02-springcloud(理论篇一) ...

  8. 14 微服务电商【黑马乐优商城】:day02-springcloud(理论篇四:配置Robbin负载均衡)

    本项目的笔记和资料的Download,请点击这一句话自行获取. day01-springboot(理论篇) :day01-springboot(实践篇) day02-springcloud(理论篇一) ...

  9. 14 微服务电商【黑马乐优商城】:day02-springcloud(搭建Eureka注册中心)

    本项目的笔记和资料的Download,请点击这一句话自行获取. day01-springboot(理论篇) :day01-springboot(实践篇) day02-springcloud(理论篇一) ...

随机推荐

  1. SourceTree - 对Git的使用

    SourceTree - 对Git的使用 一 .SourceTree简介 SourceTree 是 Windows 和Mac OS X 下免费的 Git 和 Hg 客户端,拥有可视化界面,容易上手操作 ...

  2. QSignalMapper is deprecated

    今天参考 qt4 的书籍,在 qt5 的平台上面,用了 QSignalMapper,结果收到警告" QSignalMapper is deprecated". 经过一番查找,找到了 ...

  3. 吴裕雄--天生自然Django框架开发笔记:Django Nginx+uwsgi 安装配置

    Django Nginx+uwsgi 安装配置 使用 python manage.py runserver 来运行服务器.这只适用测试环境中使用. 正式发布的服务,需要一个可以稳定而持续的服务器,比如 ...

  4. HyperLedger Cello学习笔记

    HyperLedger Cello学习笔记 转载请注明出处:HyperLedger Cello学习笔记 概述 Hyperledger Cello是Hyperledger下的一个子项目,其主要功能如下: ...

  5. ES系列之Promise async 和 await

    概述 promise是异步编程的一种解决方案,比传统的解决方案—回调函数和事件—更合理更强大. 所谓的promise就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作的结果). Pro ...

  6. ES6 之 第七种数据类型Symbol

    概述 为了减少对象的属性名冲突,ES6引入新的原始数据类型Symbol,JS的第七种数据类型. Symbol 能够保证每个属性的名字都是独一无二,这样就能从根本上防止属性名冲突. Symbol 值能够 ...

  7. ZJNU 2356 - 六学家

    “选出来三个六学家,他们的编号是i,j,k,满足i<j<k,且a[k]=a[j]-a[i]” 所以输入第i个数a[i]时,直接让答案加上前i-1个数中能构成差值为a[i]的数量即可 然后让 ...

  8. ubuntu 插网线无法上网解决方案

    前言 不知道最近是什么情况,ubuntu链接网线总是上不去网,但是wifi还能用,一直也就没有捣鼓,不过今天连wifi都不能用了,只能开始修理了. 修复方案 使用ifconfig命令查看以太网的名称 ...

  9. Android 公告新闻消息资讯之垂直滚动效果

    垂直滚动新闻栏的实现原理: 就是一个自定义的LinearLayout,并且textView能够循环垂直滚动,而且条目可以点击,显示区域最多显示2个条目,并且还有交替的属性垂直移动的动画效果,通过线程来 ...

  10. rpc框架解释

    远程过程调用协议RPC(Remote Procedure Call Protocol) RPC是指远程过程调用,也就是说两台服务器A,B,一个应用部署在A服务器上,想要调用B服务器上应用提供的函数/方 ...