api-gateway

本模块演示api gateway,通过Zuul实现。

url desc
http://localhost:8080/api/swagger/api/hello 访问eureka-client服务的hello方法
http://localhost:8080/rest/api/user 获取db-rest服务的User列表
... ...

启用Zuul

  • 引入Maven依赖

    org.springframework.cloud
    spring-cloud-starter-zuul

  • 配置接口

serviceId指定服务名
url指定服务地址

zuul.routes.eureka-client.path = /swagger/**
zuul.routes.eureka-client.serviceId = eureka-client
# stripPrefix:是否去除前缀,默认为true
# stripPrefix=true, http://localhost:8080/api/swagger/api/hello ==> http://localhost:8081/api/hello
# stripPrefix=false, http://localhost:8080/api/swagger/api/hello ==> http://localhost:8081/api/swagger/api/hello
zuul.routes.eureka-client.stripPrefix = true

zuul.routes.rest-demo.path = /rest/**
zuul.routes.rest-demo.url = http://localhost:8082/

最好还设置下Hystrix的全局超时时间,如下,设置默认超时时间为60s

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 60000
  • 启用Zuul

增加@EnableZuulProxy注解,启用Zuul

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