004 springCloudAlibaba Gateway

2024-05-02 16:28

本文主要是介绍004 springCloudAlibaba Gateway,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • gatewayServer
      • GatewayServerApplication.java
      • ServletInitializer.java
      • application.yaml
      • pom.xml
    • orderServer
      • OrderController.java
      • ProductClient.java
      • OrderServerApplication.java
      • ServletInitializer.java
      • application.yaml
      • pom.xml
    • productServer
      • ProductController.java
      • Product.java
      • ProductServerApplication.java
      • ServletInitializer.java
      • application.yaml
      • pom.xml
    • pom.xml

gatewayServer

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


package com.example;import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;public class ServletInitializer extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(GatewayServerApplication.class);}}

application.yaml


#服务名称 端口
server:port: 9090
spring:application:name: gatewayServercloud:nacos:  # nacos urldiscovery:server-addr: localhost:8848sentinel: #sentinel urltransport:dashboard: localhost:8080gateway:   # gatewaydiscovery:locator:enabled: true #开启gateway从nacos上获取服务列表routes:- id: order_routeuri: lb://orderServer # 假设orderServer已经在服务注册中心(如Nacos)注册predicates:- Path=/order/**- Method=GET,POST- Before=2025-07-09T17:42:47.789-07:00[Asia/Shanghai]- id: product_routeuri: lb://productServer # 假设productServer已经在服务注册中心(如Nacos)注册predicates:- Path=/product/**feign:sentinel:enabled: true

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


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;@Autowiredprivate ProductClient productClient;@GetMapping("save")public String save(){//在订单中 要有商品的信息 proId = 9Integer 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


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


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


package com.example;import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;public class ServletInitializer extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(OrderServerApplication.class);}}

application.yaml


server:port: 9001spring:application:name: orderServercloud:nacos:server-addr: localhost:8848 # ?????URLsentinel:transport:dashboard: localhost:8080 #??Sentinel dashboard??port: 8719management:endpoints:web:exposure:include: '*'feign:sentinel:enabled: true # ??Sentinel?Feign???

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


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


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;}@Overridepublic String toString() {return "Product{" +"productId=" + productId +", producutName='" + producutName + '\'' +", producutPrice=" + producutPrice +", producutImg='" + producutImg + '\'' +'}';}
}

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


package com.example;import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;public class ServletInitializer extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(ProductServerApplication.class);}}

application.yaml


server:port: 7001spring:application:name: productServercloud:nacos:server-addr: localhost:8848  # ???? nacos ???sentinel:transport:dashboard: localhost:8080 #??Sentinel dashboard??port: 8719management:endpoints:web:exposure:include: '*'feign:sentinel:enabled: true # ??Sentinel?Feign???

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

这篇关于004 springCloudAlibaba Gateway的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/954674

相关文章

springboot将lib和jar分离的操作方法

《springboot将lib和jar分离的操作方法》本文介绍了如何通过优化pom.xml配置来减小SpringBoot项目的jar包大小,主要通过使用spring-boot-maven-plugin... 遇到一个问题,就是每次maven package或者maven install后target中的ja

Java中八大包装类举例详解(通俗易懂)

《Java中八大包装类举例详解(通俗易懂)》:本文主要介绍Java中的包装类,包括它们的作用、特点、用途以及如何进行装箱和拆箱,包装类还提供了许多实用方法,如转换、获取基本类型值、比较和类型检测,... 目录一、包装类(Wrapper Class)1、简要介绍2、包装类特点3、包装类用途二、装箱和拆箱1、装

如何利用Java获取当天的开始和结束时间

《如何利用Java获取当天的开始和结束时间》:本文主要介绍如何使用Java8的LocalDate和LocalDateTime类获取指定日期的开始和结束时间,展示了如何通过这些类进行日期和时间的处... 目录前言1. Java日期时间API概述2. 获取当天的开始和结束时间代码解析运行结果3. 总结前言在J

Java深度学习库DJL实现Python的NumPy方式

《Java深度学习库DJL实现Python的NumPy方式》本文介绍了DJL库的背景和基本功能,包括NDArray的创建、数学运算、数据获取和设置等,同时,还展示了如何使用NDArray进行数据预处理... 目录1 NDArray 的背景介绍1.1 架构2 JavaDJL使用2.1 安装DJL2.2 基本操

最长公共子序列问题的深度分析与Java实现方式

《最长公共子序列问题的深度分析与Java实现方式》本文详细介绍了最长公共子序列(LCS)问题,包括其概念、暴力解法、动态规划解法,并提供了Java代码实现,暴力解法虽然简单,但在大数据处理中效率较低,... 目录最长公共子序列问题概述问题理解与示例分析暴力解法思路与示例代码动态规划解法DP 表的构建与意义动

Java多线程父线程向子线程传值问题及解决

《Java多线程父线程向子线程传值问题及解决》文章总结了5种解决父子之间数据传递困扰的解决方案,包括ThreadLocal+TaskDecorator、UserUtils、CustomTaskDeco... 目录1 背景2 ThreadLocal+TaskDecorator3 RequestContextH

关于Spring @Bean 相同加载顺序不同结果不同的问题记录

《关于Spring@Bean相同加载顺序不同结果不同的问题记录》本文主要探讨了在Spring5.1.3.RELEASE版本下,当有两个全注解类定义相同类型的Bean时,由于加载顺序不同,最终生成的... 目录问题说明测试输出1测试输出2@Bean注解的BeanDefiChina编程nition加入时机总结问题说明

java父子线程之间实现共享传递数据

《java父子线程之间实现共享传递数据》本文介绍了Java中父子线程间共享传递数据的几种方法,包括ThreadLocal变量、并发集合和内存队列或消息队列,并提醒注意并发安全问题... 目录通过 ThreadLocal 变量共享数据通过并发集合共享数据通过内存队列或消息队列共享数据注意并发安全问题总结在 J

Spring AI Alibaba接入大模型时的依赖问题小结

《SpringAIAlibaba接入大模型时的依赖问题小结》文章介绍了如何在pom.xml文件中配置SpringAIAlibaba依赖,并提供了一个示例pom.xml文件,同时,建议将Maven仓... 目录(一)pom.XML文件:(二)application.yml配置文件(一)pom.xml文件:首

SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤

《SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤》本文主要介绍了SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤,文中通过示例代码介绍的非常详... 目录 目标 步骤 1:确保 ProxySQL 和 mysql 主从同步已正确配置ProxySQL 的