spring cloud zuul 集成 spring config、eureka 实现动态路由

别说谁变了你拦得住时间么 提交于 2019-12-03 03:58:28

1.添加相关依赖包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hht.zool</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR3</spring-cloud.version>
    </properties>

    <dependencies>
        <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>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>2.1.4.RELEASE</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.添加bootstrap.properties

实现配置通过配置中心加载,配置中心搭建和eureka server搭建参考

https://my.oschina.net/haitaohu/blog/3104975  服务注册中心

https://my.oschina.net/haitaohu/blog/3045510 配置中心

# Eureka 服务器地址
eureka.client.serviceUrl.defaultZone= http://localhost:12346/eureka
eureka.instance.prefer-ip-address=true
eureka.instance.ip-address=192.168.1.122


### bootstrap 上下文配置
### 集成 eureka 取代直接 配置 uri
spring.cloud.config.discovery.enabled=true
#配置 config server 应用名称
spring.cloud.config.discovery.serviceId = config-server

# 配置客户端应用名称:{application}
spring.cloud.config.name = zuul
# profile 是激活配置
spring.cloud.config.profile = dev
# label 在Git中指的分支名称
spring.cloud.config.label = master 


3.启动类,这里没有使用spring cloud bus,简单通过定时器来抓取新的配置路由规则,因为需要依赖 rabbit mq或者 kafka 生产环境最好使用,或者把配置中心缓换成 携程的Apollo

package com.hht.zool;

import com.hht.zool.filter.TokenFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;

/**
 * @author hht
 * @ClassName com.hht.zool.ZoolApplication
 * @Description TODO
 * @Date 2019/9/17 16:29
 * @VERSION 1.0
 */
@SpringBootApplication
@EnableZuulProxy
@EnableScheduling
@EnableDiscoveryClient
public class ZoolApplication {
    public static void main(String[] args) {
        SpringApplication.run(ZoolApplication.class);
    }


    //过滤器测试
    @Bean
    public TokenFilter tokenFilter() {
        return new TokenFilter();
    }

    //动态刷新路由
    @RefreshScope
    @ConfigurationProperties("zuul")
    public ZuulProperties zuulProperties(){
        return new ZuulProperties();
    }

    private ContextRefresher refresher;

    public ZoolApplication(ContextRefresher refresher){
        this.refresher = refresher;

    }

    /**
     * @Description 初始化后延时 3秒运行 ,然后 每隔 5秒 执行一次
     * @Date 16:24 2019/4/29
     * @Param []
     * @return void
     **/
    @Scheduled(fixedRate = 5 * 1000,initialDelay =  30 * 1000)
    public void autoRefresh(){
        System.out.println(new Date());
        refresher.refresh();
    }
}

额外代码(测试,过滤器添加)

package com.hht.zool.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hht
 * @ClassName TokenFilter
 * @Description TODO
 * @Date 2019/9/19 11:46
 * @VERSION 1.0
 */
public class TokenFilter extends ZuulFilter {

    /**
     * 过滤器的类型,它决定过滤器在请求的哪个生命周期中执行。
     * 这里定义为pre,代表会在请求被路由之前执行。
     *
     * @return
     */

    public String filterType() {
        return "pre";
    }

    /**
     * filter执行顺序,通过数字指定。
     * 数字越大,优先级越低。
     *
     * @return
     */

    public int filterOrder() {
        return 0;
    }

    /**
     * 判断该过滤器是否需要被执行。这里我们直接返回了true,因此该过滤器对所有请求都会生效。
     * 实际运用中我们可以利用该函数来指定过滤器的有效范围。
     *
     * @return
     */

    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器的具体逻辑
     *
     * @return
     */

    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        String token = request.getParameter("token");
        if (token == null || token.isEmpty()) {
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody("token is empty");
        }
        return null;
    }
}


 

路由规则配置文件 zuul-dev.properties 如下:

zuul.routes.user-service-client=/ucenter/**

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!