07--springCloudAlibab gateway 网关

  1. 在spring-cloud-alibaba项目中像创建gateway-example模块
  2. 引入gateway开发包
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-cloud-alibaba</artifactId>
        <groupId>spring-cloud-alibaba</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>gateway-example</artifactId>

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

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.cloud.alibaba.GatewayApplication</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
  1. bootstrap.yml
spring:
  application:
    name: gateway-example
  profiles:
    active: dev
  main:
    allow-bean-definition-overriding: true
  cloud:
    nacos:
      discovery:
        # 服务注册地址
        server-addr: 101.37.152.195:8848
      config:
        server-addr: 101.37.152.195:8848
        # 配置文件格式
        file-extension: yml
        # 共享配置
        shared-dataids: application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
  1. nacos配置
Data ID: gateway-example.yml
Group:DEFAULT_GROUP
配置格式:YAML
配置内容:
spring:
  cloud:
    gateway:
      filter:
        remove-non-proxy-headers:
          headers:
      routes:
        - id:  producer-example
          uri: lb://producer-example
          predicates:
            - Path=/producer/**
          # StripPrefix=1,否则访问服务时会带上producer
          filters:
            - StripPrefix=1
server:
  port: 10004

/producer/**请求 转发至producer-example服务的 /**接口
4. 配置gateway异常处理器

package com.cloud.alibaba.config.handler;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 网关统一异常处理
 *
 * @author
 */
@Order(-1)
@Configuration
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GatewayExceptionHandler.class);

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        ResponseStatusException responseStatusException = null;

        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        }

        String msg;

        if (ex instanceof NotFoundException) {
            msg = "服务未找到";
        } else if (ex instanceof ResponseStatusException) {
            responseStatusException = (ResponseStatusException) ex;
            msg = responseStatusException.getMessage();
        } else {
            msg = "内部服务器错误";
        }

        log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex.getMessage());

        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        response.setStatusCode(HttpStatus.OK);

        if (responseStatusException != null) {
            ResponseStatusException finalResponseStatusException = responseStatusException;
            return response.writeWith(Mono.fromSupplier(() -> getDataBuffer(response, msg, finalResponseStatusException.getStatus().value())));
        } else {
            return response.writeWith(Mono.fromSupplier(() -> getDataBuffer(response, msg, 500)));
        }


    }

    private DataBuffer getDataBuffer(ServerHttpResponse response, String msg, int status) {
        DataBufferFactory bufferFactory = response.bufferFactory();
        Map<String, Object> map = new HashMap<>(2);
        map.put("status", status);
        map.put("msg", msg);
        return bufferFactory.wrap(JSON.toJSONBytes(map));
    }
}
  1. 启动类
package com.cloud.alibaba;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @author 刘志强
 * @date 2020/11/19 09:34
 */
@EnableDiscoveryClient
@SpringBootApplication
@Slf4j
public class GatewayApplication implements CommandLineRunner {


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

    @Override
    public void run(String... args) {
        log.info("gateway已启动");
    }

}

  1. 启动producer-example 和 gateway-example服务
  2. 访问 http://xxx.xx.xx.xx:10004/producer/getUserName
  3. 关闭producer-example 访问 http://xxx.xx.xx.xx:10004/producer/getUserName 观察响应
源码地址
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值