Spring cloud Zul integrates spring config and eureka to realize dynamic routing

1. Add dependent package

<?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. Add bootstrap.properties

To realize the configuration, load the configuration center, build the configuration center and build the eureka server for reference

https://my.oschina.net/haitaohu/blog/3104975 service registry

https://my.oschina.net/haitaohu/blog/3045510 configuration center

# Eureka server address
eureka.client.serviceUrl.defaultZone= http://localhost:12346/eureka
eureka.instance.prefer-ip-address=true
eureka.instance.ip-address=192.168.1.122


### bootstrap context configuration
### Integration of eureka instead of direct configuration uri
spring.cloud.config.discovery.enabled=true
#Configure config server application name
spring.cloud.config.discovery.serviceId = config-server

# Configuration client application name: {application}
spring.cloud.config.name = zuul
# profile is the active configuration
spring.cloud.config.profile = dev
# The branch name that label refers to in Git
spring.cloud.config.label = master 


3. Start class. There is no spring cloud bus here. Simply use the timer to grab the new configuration routing rules. It is better to rely on rabbit mq or kafka production environment, or change the configuration center to Apollo of Ctrip

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);
    }


    //Filter test
    @Bean
    public TokenFilter tokenFilter() {
        return new TokenFilter();
    }

    //Dynamic refresh route
    @RefreshScope
    @ConfigurationProperties("zuul")
    public ZuulProperties zuulProperties(){
        return new ZuulProperties();
    }

    private ContextRefresher refresher;

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

    }

    /**
     * @Description After initialization, it is delayed for 3 seconds, and then executed every 5 seconds
     * @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();
    }
}

Extra code (test, filter add)

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 {

    /**
     * The type of filter that determines which life cycle the filter executes in the request.
     * This is defined as pre, which means the request will be executed before it is routed.
     *
     * @return
     */

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

    /**
     * filter Execution order, specified by number.
     * The higher the number, the lower the priority.
     *
     * @return
     */

    public int filterOrder() {
        return 0;
    }

    /**
     * Determine whether the filter needs to be executed. Here we return true directly, so the filter will take effect on all requests.
     * In practice, we can use this function to specify the effective range of the filter.
     *
     * @return
     */

    public boolean shouldFilter() {
        return true;
    }

    /**
     * Filter specific logic
     *
     * @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;
    }
}


 

The routing rule configuration file zuul-dev.properties is as follows:

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

Keywords: Programming Spring Maven Apache Java

Added by nakins on Mon, 02 Dec 2019 00:11:38 +0200