Spring Cloud学习笔记19——如何集成 Zuul

Zuul的功能

在这里插入图片描述

集成Zuul

开发环境

  • JDK8+
  • Gradle4+
  • Redis 3.2.100
  • Spring Boot 2.0.0.M3
  • Spring Cloud Starter Netflix Eureka Client Finchley.M2
  • Spring Cloud Starter Netflix Zuul Finchley.M2

创建项目

以之前的micro-weather-eureka-client为蓝本,创建micro-weather-eureka-client-zuul项目
在这里插入图片描述

修改源码

修改build.gradle配置,添加Zuul依赖:

//依赖关系
dependencies {

    //Eureka Client
    compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client')

    //Zuul
    compile('org.springframework.cloud:spring-cloud-starter-netflix-zuul')

    //该依赖用于测试阶段
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

修改com.study.spring.cloud.weather包下的Application类,加入@EnableZuulProxy注解:

package com.study.spring.cloud.weather;

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注解声明Spring Boot应用
 * 作用等同于@Configuration, @EnableAutoConfiguration, @ComponentScan,
 * 简化Spring配置
*/
@SpringBootApplication
//启用可发现的客户端
@EnableDiscoveryClient
//启用Zuul的代理功能
@EnableZuulProxy
//Application类一定要处于整个工程的根目录下,这样它才能根据配置去扫描子节点下的Spring的Bean
public class Application {

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

修改application.properties配置文件:

#应用名称
spring.application.name=micro-weather-eureka-client-zuul

#注册服务器的URL
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/

#zuul本身的配置
#设置需要路由的URL,此处设置hi资源的路径
zuul.routes.hi.path=/hi/**
#访问hi应用时将请求转发到某应用的应用名称
zuul.routes.hi.service-id=micro-weather-eureka-client

运行

先通过IDE运行micro-weather-eureka-server

再通过命令行编译、运行micro-weather-eureka-client,注意指定运行端口(如8081),完成后可访问http://localhost:8081/hello页面:
在这里插入图片描述

最后通过IDE运行micro-weather-eureka-client-zuul,运行结果如下:
在这里插入图片描述
访问http://localhost:8080/hello页面:
在这里插入图片描述
访问http://localhost:8080/hi/hello页面:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43415405/article/details/84033815
今日推荐