前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >spring cloud zuul 集成 spring config、eureka 实现动态路由

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

作者头像
海涛
发布2019-12-02 21:36:12
7140
发布2019-12-02 21:36:12
举报
文章被收录于专栏:海涛技术日常海涛技术日常

1.添加相关依赖包

代码语言:javascript
复制
<?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://cloud.tencent.com/developer/article/1505256 服务注册中心

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

代码语言:javascript
复制
# 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

代码语言:javascript
复制
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();
    }
}

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

代码语言:javascript
复制
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/**

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
微服务引擎 TSE
微服务引擎(Tencent Cloud Service Engine)提供开箱即用的云上全场景微服务解决方案。支持开源增强的云原生注册配置中心(Zookeeper、Nacos 和 Apollo),北极星网格(腾讯自研并开源的 PolarisMesh)、云原生 API 网关(Kong)以及微服务应用托管的弹性微服务平台。微服务引擎完全兼容开源版本的使用方式,在功能、可用性和可运维性等多个方面进行增强。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档