spring-gateway-通过服务名称访问微服务
工程目录
- cloud-eureka-server: 注册中心
- foundation-consumer: 消费者
- foundation-gateway-server: 网关
cloud-eureka-server
applicatioin.yml
:
spring:
application:
name: eureka-server
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
fetch-registry: false
register-with-eureka: false
foundation-consumer
application.yml
:
spring:
application:
name: foundation-consumer
server:
port: 8080
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
fetch-registry: true
register-with-eureka: true
controller
:
@RestController
public class HelloController {
@GetMapping("/echo/{name}")
public String echo(@PathVariable("name") String name){
return "hello: ".concat(name);
}
}
foundation-gateway-server
application.yml
:
spring:
application:
name: foundation-gateway-server
cloud:
gateway:
routes:
- id: rt_consumer
uri: lb://foundation-consumer
predicates:
- Path=/h5/sc/**
filters:
# 不需要拼接 /h5/sc
- StripPrefix=2
discovery:
# locator需要打开,不然通过 lb://.. 方式请求不到
locator:
enabled: true
lower-case-service-id: true
server:
port: 9090
eureka:
instance:
hostname: localhost
client:
service-url:
defaultZone: http://localhost:8761/eureka/
# 这个不能是false, 需要向注册中心拉取服务信息
fetch-registry: true
访问服务
现在可以访问:
http://localhost:9090/foundation-gateway-server/h5/sc/echo/tom
或者:
http://localhost:9090/h5/sc/echo/tom