004 springCloudAlibaba Gateway

文章目录

gatewayServer

GatewayServerApplication.java

java 复制代码
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class GatewayServerApplication {

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

}

ServletInitializer.java

java 复制代码
package com.example;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(GatewayServerApplication.class);
    }

}

application.yaml

yaml 复制代码
#服务名称 端口
server:
  port: 9090
spring:
  application:
    name: gatewayServer
  cloud:
    nacos:  # nacos url
      discovery:
        server-addr: localhost:8848
    sentinel: #sentinel url
      transport:
        dashboard: localhost:8080
    gateway:   # gateway
      discovery:
        locator:
          enabled: true #开启gateway从nacos上获取服务列表
      routes:
        - id: order_route
          uri: lb://orderServer # 假设orderServer已经在服务注册中心(如Nacos)注册
          predicates:
            - Path=/order/**
            - Method=GET,POST
            - Before=2025-07-09T17:42:47.789-07:00[Asia/Shanghai]


        - id: product_route
          uri: lb://productServer # 假设productServer已经在服务注册中心(如Nacos)注册
          predicates:
            - Path=/product/**

feign:
  sentinel:
    enabled: true

pom.xml

xml 复制代码
<?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.example</groupId>
        <artifactId>springCloudAlibaba</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>gatewayServer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>gatewayServer</name>
    <description>gatewayServer</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

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

        <!--SpringCloud ailibaba sentinel -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>


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

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

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



        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </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>

orderServer

OrderController.java

java 复制代码
package com.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("order")
public class OrderController {

    @Value("${server.port}")
    private String serverPort;

    @Autowired
    private ProductClient productClient;


    @GetMapping("save")
    public String save(){
        //在订单中 要有商品的信息 proId = 9
        Integer proId = 9;
        String productResult = productClient.getProductById(proId);
        System.out.println("在订单中 要有商品的信息 proId = "+proId + productResult);
        //return "订单服务"+serverPort+"正在下订单";
        return "订单服务 "+serverPort+" "+productResult;
    }



//    @GetMapping("order/{orderId}")
//    public String getById(@PathVariable("orderId") Integer orderId){
//        System.out.println("订单服务port="+serverPort+"上查询id="+orderId+"的订单");
//        return "port:"+serverPort +"查询到id="+orderId+"的订单";
//    }

}

ProductClient.java

java 复制代码
package com.example.controller;


import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient("productServer")
public interface ProductClient {

    @GetMapping("product/{proId}")
    public String getProductById(@PathVariable("proId") Integer proId);

}

OrderServerApplication.java

java 复制代码
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class OrderServerApplication {

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

}

ServletInitializer.java

java 复制代码
package com.example;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(OrderServerApplication.class);
    }

}

application.yaml

yaml 复制代码
server:
  port: 9001


spring:
  application:
    name: orderServer
  cloud:
    nacos:
      server-addr: localhost:8848 # ?????URL
    sentinel:
      transport:
        dashboard: localhost:8080 #??Sentinel dashboard??
        port: 8719

management:
  endpoints:
    web:
      exposure:
        include: '*'

feign:
  sentinel:
    enabled: true # ??Sentinel?Feign???

pom.xml

xml 复制代码
<?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.example</groupId>
        <artifactId>springCloudAlibaba</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>orderServer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>orderServer</name>
    <description>orderServer</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>


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



        <!--        内置了 LoadBalancer 负载均衡器-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-loadbalancer</artifactId>
        </dependency>

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



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


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </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>

productServer

ProductController.java

java 复制代码
package com.example.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.entity.Product;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("product")
public class ProductController {

    @Value("${server.port}")
    private Integer serverPort;

    @GetMapping("/{proId}")
    @SentinelResource(value = "getById",blockHandler = "handleBlock",fallback = "handleFallback")
    public String getById(@PathVariable("proId") Integer proId){

        Product product = new Product(proId,"保温杯",69.9F,"images/cup.png");
        System.out.println("商品服务"+serverPort+"正在查询商品:"+proId);
        //int i = 10/0;
        return product.toString();
    }


    /**
     * 违背流控规则,blockHandler
     * product/{proId}
     * 有流控规则,QPS <= 1
     * 若超过流量阈值,blockHandler
     */
    public String handleBlock(@PathVariable("proId") Integer proId, BlockException exception) {
        return "商品查询请求QPS>1,超过流量阈值";
    }

    /**
     * 业务有异常,fallback
     */
    public String handleFallback(@PathVariable("proId") Integer proId,Throwable e) {
        Product product = new Product();
        product.setProductId(proId);
        product.setProducutName("保温杯");
        return "[fallback]商品查询的信息是:" + product;
    }



}

Product.java

java 复制代码
package com.example.entity;

public class Product {
    private Integer productId;
    private String producutName;
    private Float producutPrice;
    private String producutImg;
    public Product(){}
    public Product(Integer productId, String producutName, Float producutPrice, String producutImg) {
        this.productId = productId;
        this.producutName = producutName;
        this.producutPrice = producutPrice;
        this.producutImg = producutImg;
    }

    public Integer getProductId() {
        return productId;
    }

    public void setProductId(Integer productId) {
        this.productId = productId;
    }

    public String getProducutName() {
        return producutName;
    }

    public void setProducutName(String producutName) {
        this.producutName = producutName;
    }

    public Float getProducutPrice() {
        return producutPrice;
    }

    public void setProducutPrice(Float producutPrice) {
        this.producutPrice = producutPrice;
    }

    public String getProducutImg() {
        return producutImg;
    }

    public void setProducutImg(String producutImg) {
        this.producutImg = producutImg;
    }

    @Override
    public String toString() {
        return "Product{" +
                "productId=" + productId +
                ", producutName='" + producutName + '\'' +
                ", producutPrice=" + producutPrice +
                ", producutImg='" + producutImg + '\'' +
                '}';
    }
}

ProductServerApplication.java

java 复制代码
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class ProductServerApplication {

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

}

ServletInitializer.java

java 复制代码
package com.example;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(ProductServerApplication.class);
    }

}

application.yaml

java 复制代码
server:
  port: 7001

spring:
  application:
    name: productServer
  cloud:
    nacos:
      server-addr: localhost:8848  # ???? nacos ???
    sentinel:
      transport:
        dashboard: localhost:8080 #??Sentinel dashboard??
        port: 8719

management:
  endpoints:
    web:
      exposure:
        include: '*'

feign:
  sentinel:
    enabled: true # ??Sentinel?Feign???

pom.xml

xml 复制代码
<?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.example</groupId>
        <artifactId>springCloudAlibaba</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>productServer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>productServer</name>
    <description>productServer</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

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



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


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


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </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>

pom.xml

xml 复制代码
<?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.7.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springCloudAlibaba</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <name>springCloudAlibaba</name>
    <description>springCloudAlibaba</description>

    <modules>
        <module>orderServer</module>
        <module>productServer</module>
        <module>gatewayServer</module>
    </modules>

    <packaging>pom</packaging>
    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>2021.0.4</spring-cloud.version>
        <spring-cloud-alibaba.version>2021.0.4.0</spring-cloud-alibaba.version>
    </properties>



    <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>
            <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>



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

</project>
相关推荐
菜菜-plus15 小时前
分布式,微服务,SpringCloudAlibaba,nacos,gateway,openFeign
java·分布式·微服务·nacos·gateway·springcloud·openfeign
七月在野,八月在宇,九月在户15 小时前
前端--> nginx-->gateway产生的跨域问题分析
前端·nginx·gateway
Denny辉2 天前
Flink使用SQL Gateway提交SQL Job到远程集群
sql·flink·gateway
菜菜-plus3 天前
Nginx、Gateway的区别
运维·nginx·gateway
cyt涛4 天前
SpringCloudGateway — 网关登录校验
运维·网关·gateway·登录·过滤器·校验·threadlocal
牛角上的男孩6 天前
Istio Gateway发布服务
云原生·gateway·istio
柳叶寒8 天前
医院信息化与智能化系统(17)
java·nacos·gateway·全栈·项目
cyt涛9 天前
SpringCloudGateway — 网关路由
java·开发语言·网关·gateway·路由·断言·转发
代码魔法师Sunny11 天前
502 Bad Gateway 错误详解:从表现推测原因,逐步排查直至解决
gateway
RedCong12 天前
通过route访问Openshift上的HTTP request报错504 Gateway Time-out【已解决】
http·gateway·openshift