SpringCloud:扩展zuul配置路由访问

 

继续上次整合SpringCloud的demo进行扩展zuul:https://www.cnblogs.com/nhdlb/p/12555968.html 

这里我把zuul划分出一个模块单独启动

 

创建模块

 

 

引入依赖

直接在ZuulServer模块内的pom文件引入就可以

<dependencies>
        <!-- netflix-zuul路由服务 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!-- hystrix服务 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
    </dependencies>

zuul的版本和cloud的版本是匹配的,可以参照文章开头的链接访问查看项目版本。

 

编写启动类

编写ZuulServerApplication启动类

package com.boot.zuul;

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

//springboot启动注解 @SpringBootApplication
//由于没有链接数据库,所以暂时不加载,否则报错 @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) //zuul服务启动注解 @EnableZuulProxy public class ZuulServerApplication { public static void main(String[] args){ System.out.println(">>>>>>>>>>>>>>> 启动ZuulServer <<<<<<<<<<<<<<<"); SpringApplication.run(ZuulServerApplication.class, args); System.out.println(">>>>>>>>>>>>>>> 运行ZuulServer成功 <<<<<<<<<<<<<<<"); } }

 

创建application.properties配置文件

#指定自己实例的名称(刚才消费者指定的名称)
spring.application.name=zuul-server
#端口号
server.port=8004
#注册地址
eureka.client.serviceUrl.defaultZone = http://localhost:8001/eureka/

#配置zuul路由规则
#配置对外访问路径前缀
zuul.routes.eureka-consumer.path=/consumer/**
#配置微服务的名称(就是其他服务的spring.application.name 名称)
zuul.routes.eureka-consumer.serviceId=eureka-consumer

#或者配置微服务的访问IP路径及端口
#zuul.routes.eureka-consumer.url=http://192.168.200.16:8002

 

测试

启动服务

 

以前访问consumer服务的路径为:localhost:8002/Consumer/gotoAlgorithmServer

 

这次用zuul-server服务测试能否调通consumer和provider服务,访问路径:localhost:8004/consumer/Consumer/gotoAlgorithmServer

调用成功!

 

注意:没有配置zuul路由服务时,我们直接访问consumer(消费者)服务路径,这样我们的访问路径就暴露在外并不安全,配置zuul路由服务后,通过映射规则添加访问路径前缀且对外暴露的服务就只需zuul-server服务,当有多个consumer(消费者)时也可以结合配置项实现负载均衡,所谓一举多得。

 

posted @ 2020-03-31 11:01  怒吼的萝卜  阅读(559)  评论(0编辑  收藏  举报