spring-cloud 学习四 服务网关

  API Gateway

  服务网关在微服务中是一个很重要的组成部分,通过服务网关可以统一向外提供REST API,例如 / 映射到后端应用 /api/user 映射到 user service,  /api/comment 映射到comment service,在spring cloud中通过集成zuul来实现这个 gateway,他提供一下功能

    • Authentication
    • Insights
    • Stress Testing
    • Canary Testing
    • Dynamic Routing
    • Service Migration
    • Load Shedding
    • Security
    • Static Response handling
    • Active/Active traffic management

  

  我们使用两个服务,我们以user-provider-service来进行测试

  我们访问http://localhost:8081/users 可以看到如下输出,8081 就是user-provider-service服务的端口

 
[{"id":"1","name":"陈七","tel":null},{"id":"2","name":"王六","tel":null}]

  

  建一个api-gateway module

  pom文件

  

  <parent>
        <groupId>com.dh.cloud</groupId>
        <artifactId>spring-cloud-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>


    <dependencies>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-netflix-sidecar</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter</artifactId>
        </dependency>

    </dependencies>
View Code

 

 启动类

 

@SpringBootApplication
@EnableSidecar
public class AppGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(AppGatewayApplication.class, args);
    }

}
View Code

 

application.yml

server:
  port: 10000

sidecar:
  port: 8000

endpoints:
  restart:
    enabled: true
  shutdown:
    enabled: true
  health:
    sensitive: false

eureka:
  instance:
    hostname: gateway
  client:
    registerWithEureka: true
    fetchRegistry: true
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
View Code

 

bootstrap.yml

  

spring:
  application:
    name: api-gateway
  cloud:
    config:
      uri: http://localhost:8888
encrypt:
  failOnError: false
View Code

 

 

这里使用的都是默认配置,运行代码

访问http://localhost:10000/user-provider-service/users,10000为gateway的端口

看到输出

[{"id":"1","name":"陈七","tel":null},{"id":"2","name":"王六","tel":null}]

和直接访问服务一致,到此zuul一个简单的演示就完成了

 

posted on 2016-11-02 14:03  modprobe  阅读(354)  评论(0编辑  收藏  举报