弊端说明

实际情况下为了安全性考虑,建议 spring.cloud.gateway.discovery.locator.enabled设置为false, 这样就不对外暴露微服务名称,微服务属于内部的服务,没有必要暴露给前端,如果暴露给前端之后,前端调用接口用微服务名称去调用接口的话,那么就会出现一系列维护的问题,比如说前端直接在前的代码写死你微服务名称去调用的,那么后续就不能修改服务名了.

代码地址

https://gitee.com/zjj19941/ZJJ_Neaten5.10/tree/master/ZJJ_Gateway/demo01

配置

spring.cloud.gateway.discovery.locator.enabled默认为false,设为true开启通过微服务创建路由的功能,即可以通过微服务名访问服务

  1. spring:
  2. application:
  3. name: mall-gateway
  4. #配置nacos注册中心地址
  5. cloud:
  6. nacos:
  7. discovery:
  8. server-addr: zjj101:8848
  9. gateway:
  10. discovery:
  11. locator:
  12. # 默认为false,设为true开启通过微服务创建路由的功能,即可以通过微服务名访问服务
  13. # http://localhost:8888/mall-order/order/findOrderByUserId/1
  14. enabled: true
  15. # 是否开启网关
  16. enabled: true

测试

http://localhost:8888/mall-order/order/findOrderByUserId/1

直接通过mall-order去nacos找到对应的服务,然后去访问了

image.png
结果

  1. {
  2. "msg": "success",
  3. "code": 0,
  4. "orders": [
  5. {
  6. "id": 1,
  7. "userId": "1",
  8. "commodityCode": "1",
  9. "count": 1,
  10. "amount": 1
  11. }
  12. ]
  13. }