springCloud(7)----zuul

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_23490433/article/details/89196000

zuul的主要功能有2大类,一类是路由转发,一类是过滤器。

路由功能是微服务的一部分,比如/api/user转发到user服务,/api/goods转发到goods服务。

zuul默认和Ribbon结合实现了负载功能。

1、zuul实现路由转发功能,步骤如下:

步骤1、创建maven工程service-zuul,结构图如下:

步骤2、修改pom.xml,内容如下:

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

	</dependencies>

步骤3、在应用程序启动类上加上注解@EnableZuulProxy,开启zuul功能

package com.cn.eurekazuul;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@SpringBootApplication
@EnableZuulProxy   //开启zuul功能
@EnableEurekaClient
@EnableDiscoveryClient
public class EurekaZuulApplication {
	public static void main(String[] args) {
		SpringApplication.run(EurekaZuulApplication.class, args);
	}
}

步骤4、修改application.yml,内容如下:

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8501/eureka/
      
server:
  port: 8507
spring:
  application:
    name: eureka-zuul

zuul:
  routes:
    api-a:
      path: /api-a/**
      serviceId: service-ribbon

    api-b:
      path: /api-b/**
      serviceId: eureka-feign

注:以/api-a/开头的请求都会转发给service-ribbon服务,以/api-b/开头的请求都会转发给service-feign服务。

步骤5:在eureka-ribbon和eureka-feign服务的HelloController中新增如下代码

 //获取port端口的值
    @Value("${server.port}")
    String port;

    @RequestMapping(value="/test")
    public String test(@RequestParam String name){
        return "嗨,"+name+" 我是来自:"+port+"端口";
    }

步骤6、测试

启动这5个服务,如下图

结论:访问/api-a/test和访问/api-b/test会跳转到不同的服务,说明zuul的路由转发起到作用

2、zuul实现过滤器功能,步骤如下:

zuul不仅只是路由转发功能,并且还能过滤,做一些安全验证

稍后补充.......

猜你喜欢

转载自blog.csdn.net/sinat_23490433/article/details/89196000