Spring Cloud --zuul搭建

版权声明:转载请标明出处 https://blog.csdn.net/Joe_Wang1/article/details/82869667

 Zuul的作用就是路由转发和过滤, 即将请求转发到微服务或拦截请求; Zuul默认集成了负载均衡功能。

      下面创建一个zuul工程:

      打开IntelliJ Idea ---> New Project ---> 选择Spring Initializr ---> 设置包名 ---> 勾选web、zuul、Eureka Discovery -> 设置存储路径。

一、路由:

 在入口类添加注解@EnableZuulProxy,打开Zuul 功能

package com.springcloud.zuul;

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

@SpringBootApplication
@EnableZuulProxy
@EnableDiscoveryClient
public class ZuulApplication {

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

二、 修改配置文件,指定注册中心和路由规则


#网关端口
server.port=13000
#服务名称
spring.application.name=zuul
#注册地址
eureka.client.serviceUrl.defaultZone=http://localhost:8080/eureka/
# 路由规则配置
zuul.routes.server1.path=/server1/**
# 需要和映射的Module配置文件中 spring.application.name 一致
zuul.routes.server1.serviceId=server1

三、在 模块server1中 增加controller

/**
 * Created by joe强 on 2018/9/27 15:13
 */
@RestController(value = "/server1")
public class ZuulController {
    @Value("${server.port}")
    String port;

    @RequestMapping("/server1Zuul")
    public String serverZuul() {
        return "port is" + port;
    }
}

 server1 配置如下:

#这里 和 网关 配置中的 zuul.routes.server1.serviceId 保持一致
spring.application.name=server1
server.port=8081
eureka.instance.hostname=localhost
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:8080/eureka/

    四、启动 Euaeka 注册中心,server1 和当前Zuul 网关

    访问 注册中心:http://localhost:8080/

五、访问 接口 :

http://localhost:13000/server1/server1Zuul

可以看到 zuul 进行了转发。 zuul还可以实现验签功能和自定义过滤功能, 功能跟SpringMVC的拦截器一样 后面补充!

猜你喜欢

转载自blog.csdn.net/Joe_Wang1/article/details/82869667