SpringCloudGateway沒法訪問Eureka已註冊的服務

本地SpringCloudGateway網關application.yml文件以下:
server:
port: 16620spring

spring:
application:服務器

name: album-gateway

cloud:app

gateway:
  discovery:
    locator:
      enabled: true
  routes:
    - id: album-service
      uri: lb://album-service
      predicates:
        - Path=/service/**

eureka:
instance:url

prefer-ip-address: true

client:code

service-url:
  defaultZone: http://localhost:16610/eureka/

本地搭建的SpringCloudGateway網關服務,沒法訪問在Eureka上已註冊的服務,最終分析緣由以下:請求URI爲:/service/photo/save,網關接收到的請求URI爲:/service/photo/save,轉發到目標服務器的URI沒有改變依然是/service/photo/save。server

album-service服務接收請求的Controller以下:
@Slf4j
@RestController
@RequestMapping("/photo")
public class PhotoController {ip

@Autowired
private PhotoService photoService;

@RequestMapping("/save")
public String save(){
    return photoService.save();
}

}
因此,沒法目標服務器沒法匹配處處理Controller和處理方法。
解決辦法:
添加
filters:io

  • StripPrefix=1

去除serviceId(即/service)僅轉發/photo/save到目標服務器便可。class

最終版本以下:
server:
port: 16620cli

spring:
application:

name: album-gateway

cloud:

gateway:
  discovery:
    locator:
      enabled: true
  routes:
    - id: album-service
      uri: lb://album-service
      predicates:
        - Path=/service/**
      filters:
        - StripPrefix=1

eureka:
instance:

prefer-ip-address: true

client:

service-url:
  defaultZone: http://localhost:16610/eureka/

備註:
StripPrefix:去除前綴;PrefixPath:添加前綴;

對應過濾器工廠以下:StripPrefix --- StripPrefixGatewayFilterFactoryPrefixPath --- PrefixPathGatewayFilterFactory

相關文章
相關標籤/搜索