淘先锋技术网

首页 1 2 3 4 5 6 7

Zuul – 服务网关

反向代理和负载均衡,大前置的感觉

pom

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

yml

spring:
  application:
    name: haha
server:
  port: 8082

zuul:
  host:
    connect-timeout-millis: 60000
    socket-timeout-millis: 60000
  # url匹配规则
  routes:
    auth: 
      path: /auth/**
      service-id: haha-auth
eureka:
  client: 
    service-url: 
      defaultZone: http://localhost:8081/eureka/

启动类

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

测试。

启动一个client,匹配url规则

pom

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>

yml

spring:
  application:
    # 对应zuul的url匹配规则的service-id
    name: haha-auth
server:
  port: 

eureka:
  client: 
    service-url: 
      defaultZone: http://localhost:8081/eureka/

随意编写一个controller

@RestController
public class HelloController
{

    @GetMapping("hello/{name}")
    public String hello(@PathVariable String name)
    {
        return "hi:" + name;
    }
}

启动,访问单机测试案例
http://127.0.0.1:8083/hello/aaa
结果:
这里写图片描述

# 测试zuul的反向代理

访问: http://127.0.0.1:8082/auth/hello/aaa
结果:
这里写图片描述

总结

经过以上代码,可以提现zuul的反向代理,代理规则是url匹配规则,其次还有一个强大功能,负载均衡,我们可以把测试client 复制一份,修改端口启动,再次访问zuul,其结果将会在2个启动服务负载调用,具体规则下一篇在将,

源码:戳这里