Spring Cloud Alibaba

SpringCloudGateway使用

2019-11-11  本文已影响0人  扮鬼之梦

《SpringCloudGateway使用》

微服务网关

1.父pom

<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 http://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.9.RELEASE</version>
        <relativePath/> 
    </parent>

    <groupId>com.thy</groupId>
    <artifactId>thy-base</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>
    <name>父pom</name>
    <description>依赖版本管理</description>

    <properties>
        <java.version>1.8</java.version>
        <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
        <spring-boot.version>2.1.9.RELEASE</spring-boot.version>
        <spring.cloud.version>Greenwich.SR3</spring.cloud.version>
        <spring.cloud.alibaba.version>2.1.0.RELEASE</spring.cloud.alibaba.version>
    </properties>

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

2.子pom

<?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>com.thy</groupId>
        <artifactId>thy-base</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath/> 
    </parent>

    <artifactId>gateway-service</artifactId>
    <name>gateway-service</name>
    <description>Demo project for Spring Boot</description>

    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

</project>

3.yml配置

server:
  port: 80
  
spring: 
  application: 
    # 应用名称
    name: gateway-service                    
  cloud: 
    # 使用 Naoos 作为服务注册发现
    nacos: 
      discovery: 
        server-addr: 127.0.0.1:8848
    # 路由网关配置
    gateway: 
      # 设置与服务注册发现组件结合,这样可以采用服务名的路由策略
      discovery: 
        locator: 
          enabled: true

4.启动类添加注解

通过 Spring Cloud 原生注解 @EnableDiscoveryClient 开启服务注册发现功能

@EnableDiscoveryClient

5.通过网关访问微服务

因为配置文件中配置了spring.cloud.gateway.discovery.locator.enabled = true,所以微服务可以根据(网关地址/服务名称/端点名称)来访问,示例如下

http://localhost/service-consumer/echo/hello

全局token拦截认证

1.添加拦截器

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.fastjson.JSON;

import reactor.core.publisher.Mono;
@Component
public class TokenFilter implements GlobalFilter,Ordered{

    @Override
    public int getOrder() {
        // 返回值用来指定执行的顺序,数字越小,优先级越高
        return 0;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        //获取url中的token
        MultiValueMap<String, String> requestMap = request.getQueryParams();
        String token = requestMap.getFirst("token");
        if(token == null || token.isEmpty()) {
            return this.returnData(-1, "非法请求", exchange);
        }
        //token无效则返回错误code和msg
        if (!"123456".equals(token)) {
            return this.returnData(-1, "无效的token", exchange);
        }
        
        return chain.filter(exchange);
    }


    /**
     * 返回值的封装
     * @param code
     *      返回code
     * @param msg
     *      返回提示信息
     */
    private Mono<Void> returnData(Integer code,String msg,ServerWebExchange exchange){
        ServerHttpResponse response = exchange.getResponse();
        HashMap<String, Object> data = new HashMap<String,Object>(); 
        data.put("code", code);
        data.put("msg", msg);
        
        byte[] datas =JSON.toJSONString(data).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(datas);
        
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        
        return response.writeWith(Mono.just(buffer));
    }
    
}

2.访问测试

当token不等于123456时

image

3.参考文档

spring cloud gateway 全局过滤器

上一篇下一篇

猜你喜欢

热点阅读