1.添加Gateway微服务网关

本阶段项目完成总架构图中的第五阶段,添加Gateway微服务网关,并实现Gateway的熔断降级、负载均衡、跨越配置等处理。
elm.png

1.1.创建Gateway工程

  1. 在父工程下,创建 Maven Module 子工程(工程名:gateway_server_14000;Packaging:jar)
  2. 在pom.xm文件中添加Gateway依赖
  1. <dependencies>
  2. <!--加入gateway依赖 -->
  3. <dependency>
  4. <groupId>org.springframework.cloud</groupId>
  5. <artifactId>spring-cloud-starter-gateway</artifactId>
  6. </dependency>
  7. <!--加入hystrix的依赖,gateway也要实现熔断降级 -->
  8. <dependency>
  9. <groupId>org.springframework.cloud</groupId>
  10. <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
  11. </dependency>
  12. <!-- gateway也要向Eureka注册 -->
  13. <dependency>
  14. <groupId>org.springframework.cloud</groupId>
  15. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  16. </dependency>
  17. <!--热部署 gav -->
  18. <dependency>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-devtools</artifactId>
  21. <scope>runtime</scope>
  22. <optional>true</optional>
  23. </dependency>
  24. </dependencies>
  1. 添加主启动类
    ```java package com.neusoft;

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }

  1. 4. 创建application.yml 配置文件<br />
  2. ```yaml
  3. server:
  4. port: 14000
  5. spring:
  6. application:
  7. name: gateway-server

1.2.修改application.yml 文件

修改application.yml 配置文件,为Gateway添加:全局跨越设置、全局熔断降级过滤器、所有微服务的路由配置、以及将Gateway自身向Eureka注册。

  1. server:
  2. port: 14000
  3. spring:
  4. application:
  5. name: gateway-server
  6. #下面是关于Gateway的配置
  7. cloud:
  8. gateway:
  9. globalcors: #设置全局跨域处理
  10. corsConfigurations:
  11. '[/**]':
  12. allowedOrigins: "*"
  13. allowedHeaders: "*"
  14. allowedMethods:
  15. - GET
  16. - POST
  17. - PUT
  18. - DELETE
  19. default-filters: #设置全局熔断处理
  20. - name: Hystrix
  21. args:
  22. name: fallbackcmd
  23. fallbackUri: forward:/fallback
  24. routes: #设置路由
  25. - id: userServer
  26. uri: lb://user-server
  27. predicates:
  28. - Path=/UserController/*/**
  29. - id: foodServer
  30. uri: lb://food-server
  31. predicates:
  32. - Path=/FoodController/*/**
  33. - id: businessServer
  34. uri: lb://business-server
  35. predicates:
  36. - Path=/BusinessController/*/**
  37. - id: cartServer
  38. uri: lb://cart-server
  39. predicates:
  40. - Path=/CartController/*/**
  41. - id: deliveryaddressServer
  42. uri: lb://deliveryaddress-server
  43. predicates:
  44. - Path=/DeliveryaddressController/*/**
  45. - id: ordersServer
  46. uri: lb://orders-server
  47. predicates:
  48. - Path=/OrdersController/*/**
  49. #eureka配置
  50. eureka:
  51. client:
  52. service-url:
  53. defaultZone: http://eurekaServer13000:13000/eureka/,http://eurekaServer13001:13001/eureka/
  54. instance:
  55. prefer-ip-address: true #使用ip地址向eureka server进行注册
  56. instance-id: ${spring.cloud.client.ip-address}:${server.port}
  57. lease-renewal-interval-in-seconds: 5 #续约间隔时间
  58. lease-expiration-duration-in-seconds: 15 #续约到期时间

注意:每个微服务的控制器组件上的@CrossOrigin(“*”)注解必须要删除。

1.3.创建Controller

创建Controller,并在Controller中添加降级逻辑:

  1. package com.neusoft.controller;
  2. import org.springframework.web.bind.annotation.RestController;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import com.neusoft.po.CommonResult;
  5. @RestController
  6. public class FallbackController {
  7. @RequestMapping("/fallback")
  8. public CommonResult fallback() {
  9. return new CommonResult(403,"Gateway触发了熔断降级",null);
  10. }
  11. }

1.4.创建其它微服务集群

Gateway网关创建好之后,前端所有请求都通过Gateway网关来实现。并且Gateway网关也可以实现集群调用的负载均衡。所以,这里将商家微服务、购物车微服务、订单微服务都做成集群。

1.4.1.创建商家微服务集群

在父工程下,创建 Maven Module 子工程(工程名:business_server_10301;Packaging:jar)。此工程与business_server_10200工程内容一致,除了端口不同。

  1. server:
  2. port: 10301
  3. spring:
  4. application:
  5. name: business-server
  6. #业务配置
  7. datasource:
  8. username: root
  9. password: 123
  10. url: jdbc:mysql://localhost:3306/elm?characterEncoding=utf-8
  11. driver-class-name: com.mysql.jdbc.Driver
  12. #业务配置
  13. logging:
  14. level:
  15. org.springframework: debug
  16. com.neusoft.mapper: debug
  17. #业务配置
  18. mybatis:
  19. mapper-locations: classpath:mapper/*.xml
  20. type-aliases-package: com.neusoft.po
  21. #eureka配置
  22. eureka:
  23. client:
  24. service-url:
  25. #将自己注册给defaultZone所指定的eureka server集群上
  26. defaultZone: http://eurekaServer13000:13000/eureka/,http://eurekaServer13001:13001/eureka/
  27. instance:
  28. prefer-ip-address: true #使用ip地址向eureka server进行注册
  29. instance-id: ${spring.cloud.client.ip-address}:${server.port} #设置eureka控制台中显示的注册信息
  30. lease-renewal-interval-in-seconds: 5 #续约间隔时间
  31. lease-expiration-duration-in-seconds: 15 #续约到期时间
  32. feign:
  33. hystrix:
  34. enabled: true #在feign中开启hystrix熔断机制

1.4.2.创建购物车微服务集群

在父工程下,创建 Maven Module 子工程(工程名:cart_server_10401;Packaging:jar)。此工程与cart_server_10400工程内容一致,除了端口不同。

  1. server:
  2. port: 10401
  3. spring:
  4. application:
  5. name: cart-server
  6. #业务配置
  7. datasource:
  8. username: root
  9. password: 123
  10. url: jdbc:mysql://localhost:3306/elm?characterEncoding=utf-8
  11. driver-class-name: com.mysql.jdbc.Driver
  12. #业务配置
  13. logging:
  14. level:
  15. org.springframework: debug
  16. com.neusoft.mapper: debug
  17. #业务配置
  18. mybatis:
  19. mapper-locations: classpath:mapper/*.xml
  20. type-aliases-package: com.neusoft.po
  21. #eureka配置
  22. eureka:
  23. client:
  24. service-url:
  25. #将自己注册给defaultZone所指定的eureka server集群上
  26. defaultZone: http://eurekaServer13000:13000/eureka/,http://eurekaServer13001:13001/eureka/
  27. instance:
  28. prefer-ip-address: true #使用ip地址向eureka server进行注册
  29. instance-id: ${spring.cloud.client.ip-address}:${server.port} #设置eureka控制台中显示的注册信息
  30. lease-renewal-interval-in-seconds: 5 #续约间隔时间
  31. lease-expiration-duration-in-seconds: 15 #续约到期时间

1.4.3.创建订单微服务集群

在父工程下,创建 Maven Module 子工程(工程名:orders_server_10601;Packaging:jar)。此工程与orders_server_10600工程内容一致,除了端口不同。

  1. server:
  2. port: 10601
  3. spring:
  4. application:
  5. name: orders-server
  6. #业务配置
  7. datasource:
  8. username: root
  9. password: 123
  10. url: jdbc:mysql://localhost:3306/elm?characterEncoding=utf-8
  11. driver-class-name: com.mysql.jdbc.Driver
  12. #业务配置
  13. logging:
  14. level:
  15. org.springframework: debug
  16. com.neusoft.mapper: debug
  17. #业务配置
  18. mybatis:
  19. mapper-locations: classpath:mapper/*.xml
  20. type-aliases-package: com.neusoft.po
  21. #eureka配置
  22. eureka:
  23. client:
  24. service-url:
  25. #将自己注册给defaultZone所指定的eureka server集群上
  26. defaultZone: http://eurekaServer13000:13000/eureka/,http://eurekaServer13001:13001/eureka/
  27. instance:
  28. prefer-ip-address: true #使用ip地址向eureka server进行注册
  29. instance-id: ${spring.cloud.client.ip-address}:${server.port} #设置eureka控制台中显示的注册信息
  30. lease-renewal-interval-in-seconds: 5 #续约间隔时间
  31. lease-expiration-duration-in-seconds: 15 #续约到期时间

1.5.前端工程的修改

1.5.1.修改main.js文件

  1. 添加axios基础url部分的设置。(所有请求都通过网关,所以所有请求的url基础部分都一致了)

    1. //设置axios的基础url部分
    2. axios.defaults.baseURL = 'http://localhost:14000/';
  2. 在components文件夹中创建Error403.vue组件

  1. <template>
  2. <div class="wrapper">
  3. <img src="../assets/error403.png"><br>
  4. <router-link to="/index">返回重试</router-link>
  5. </div>
  6. </template>
  7. <script>
  8. </script>
  9. <style scoped>
  10. .wrapper{
  11. text-align: center;
  12. }
  13. .wrapper img{
  14. margin: 120px 0 20px;
  15. }
  16. .wrapper a{
  17. color: #0097EF;
  18. }
  19. </style>
  1. 设置axios响应拦截器。(用于处理403状况。也就是对熔断降级响应的处理)

    1. //设置响应拦截器
    2. axios.interceptors.response.use(function(response){
    3. if(response.data.code==403){
    4. location.href = '/error403';
    5. }
    6. return response;
    7. },function(error){
    8. console.log(error);
    9. return Promise.reject(error);
    10. });
  2. Error403.vue组件不需要登陆验证,所以在路由守卫中添加配置

    1. router.beforeEach(function(to,from,next){
    2. let user = sessionStorage.getItem('user');
    3. //除了登录、注册、首页、商家列表、商家信息之外,都需要判断是否登录
    4. if(!(to.path=='/'||to.path=='/index'||to.path=='/businessList'||to.path=='/businessInfo'||to.path=='/login'||to.path=='/register'||to.path=='/error403')){
    5. if(user==null){
    6. router.push('/login');
    7. location.reload();
    8. }
    9. }
    10. next();
    11. });

1.5.2.修改所有组件的请求url

所有组件的axios请求url都要进行修改:

  1. let url = `http://localhost:10300/BusinessController/listBusinessByOrderTypeId/${this.orderTypeId}`;
  2. //修改为:
  3. let url = `BusinessController/listBusinessByOrderTypeId/${this.orderTypeId}`;

1.6.测试

前后端工程启动后进行测试。