springboot使用zuul

0

配置pom

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Brixton.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

zuul依赖

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>

启用zuul

@SpringBootApplication
@EnableZuulProxy
public class DemoApplication {

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

application.yaml

zuul:
  routes:
    demo:
      path: /demo/**
      url: forward:/demo
    product:
      path: /product/**
      stripPrefix: false

product:
  ribbon:
    listOfServers: 192.168.99.100:8080

ribbon:
  eureka:
    enabled: false

其中,使用listOfServers可以配置外部服务的多个负载均衡;使用forward可以forward到外部地址,也可以forward内部的相对地址。

配置filter

@Component
public class DemoFilter extends ZuulFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoFilter.class);

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

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            requestContext.setSendZuulResponse(false);
            throw new RuntimeException("UNAUTHORIZED");
        }
        return null;
    }
}

docs


如果觉得我的文章对你有用,请随意赞赏

你可能感兴趣的

载入中...