编写Zuul微服务网关

一 创建一个Maven工程,建立项目microservice-gateway-zuul,并为项目填写如下依赖。
    <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>
二 在启动类上添加注解@EnableZuulProxy,声明一个Zuul代理。该代理使用Ribbon来定位注册在Eureka Server中的微服务;同时,该代理还整合了Hystrix,从而实现了容错,所有经过Zuul的请求都会在Hystrix命令中执行。
package com.itmuch.cloud.study;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@SpringBootApplication
@EnableZuulProxy
public class ZuulApplication {
  public static void main(String[] args) {
    SpringApplication.run(ZuulApplication.class, args);
  }
}
三 编写配置文件application.yml
server:
  port: 8040
spring:
  application:
    name: microservice-gateway-zuul
eureka:
  client:
    service-url:
      defaultZone:http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
四 路由测试
1 启动eureka
2 启动user微服务
3 启动movie微服务
4 启动zuul
说明默认情况下,Zuul会代理所有注册到Eureka Server的微服务,并且Zuul的路由规则如下:
http://ZUUL_HOST:ZUUL_POTT/微服务在Eureka上的serviceID/**会被转发到serviceId对应的微服务。

五 负载均衡测试
1 启动eureka
2 启动多个user实例
3 启动项目zuul,此时Eureka Server首页如下:
4 多次访问 http://localhost:8040/microservice-provider-user/1,会发现两个用户微服务节点都会打印类似以下的日志:
Hibernate: select user0_.id as id1_0_0_, user0_.age as age2_0_0_, user0_.balance as balance3_0_0_, user0_.name as name4_0_0_, user0_.username as username5_0_0_ from user user0_ where user0_.id=?
说明Zuul可以使用Ribbon达到负载均衡的效果。

六 Hystrix容错与监控
1 启动eureka
2 启动user用户微服务
3 启动电影微服务
4 启动zuul
5 启动项目Dashboard
7 Hystrix Dashboard中输入http://localhost:8040/hystrix.stream,随意指定一个Title,并点击Monitor Stream按钮后,结果如下:
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值