本地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
去除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