SpringCloud2022.x集成gateway

SpringCloud2022.x集成gateway

  • 1、环境依赖
  • 2、项目代码
    • 2.1、新建springboot项目
      • 2.1.1、修改pom.xml
      • 2.1.2、修改启动类
      • 2.1.3、修改配置文件
      • 2.1.4、nacos创建配置
      • 2.1.5、新增自定义路由配置类
      • 2.1.6、新增打印日志过滤器
      • 2.1.7、启动测试

文档内容:

  • 整合gateway网关
  • 使用Nacos进行配置管理
  • 使用Nacos进行服务注册

1、环境依赖

  • JDK 17+
  • mysql 8.x
  • Nacos 2.2.0+
  • SpringBoot 3.x
  • SpringCloud 2022.0.0
  • SpringCloud Alibaba 2022.0.0.0-RC1

2、项目代码

2.1、新建springboot项目

2.1.1、修改pom.xml

父模块的pom.xml


<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.0modelVersion>

    <groupId>com.hippogroupId>
    <artifactId>java-studyartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>${project.artifactId}name>
    <packaging>pompackaging>
    <description>java学习包description>

    <modules>
        <module>study-commonsmodule>
        <module>study-gatewaymodule>
        <module>study-serviesmodule>
    modules>

    <properties>
        <java.version>17java.version>
        
        <maven.compiler.source>17maven.compiler.source>
        <maven.compiler.target>17maven.compiler.target>
        <maven.compiler.compilerVersion>17maven.compiler.compilerVersion>
        
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        
        <file.encoding>UTF-8file.encoding>
    properties>


    <dependencyManagement>
        <dependencies>
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-dependenciesartifactId>
                <version>3.0.0version>
                <type>pomtype>
                <scope>importscope>
            dependency>
            
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>2022.0.0version>
                <type>pomtype>
                <scope>importscope>
            dependency>
            
            <dependency>
                <groupId>com.alibaba.cloudgroupId>
                <artifactId>spring-cloud-alibaba-dependenciesartifactId>
                <version>2022.0.0.0-RC1version>
                <type>pomtype>
                <scope>importscope>
            dependency>
            
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <version>1.18.22version>
                <scope>providedscope>
            dependency>
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-data-mongodbartifactId>
                <version>2.3.9.RELEASEversion>
            dependency>
            
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>8.0.29version>
            dependency>
            
            <dependency>
                <groupId>cn.hutoolgroupId>
                <artifactId>hutool-coreartifactId>
                <version>5.8.11version>
            dependency>
            
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-boot-starterartifactId>
                <version>3.5.2version>
            dependency>
            
            <dependency>
                <groupId>com.hippogroupId>
                <artifactId>mongodbartifactId>
                <version>0.0.1-SNAPSHOTversion>
            dependency>
            <dependency>
                <groupId>com.hippogroupId>
                <artifactId>swagger2artifactId>
                <version>0.0.1-SNAPSHOTversion>
            dependency>
            <dependency>
                <groupId>com.hippogroupId>
                <artifactId>swagger3artifactId>
                <version>0.0.1-SNAPSHOTversion>
            dependency>
            
            <dependency>
                <groupId>io.springfoxgroupId>
                <artifactId>springfox-swagger2artifactId>
                <version>2.9.2version>
            dependency>
            <dependency>
                <groupId>io.springfoxgroupId>
                <artifactId>springfox-swagger-uiartifactId>
                <version>2.9.2version>
            dependency>
            
            <dependency>
                <groupId>io.springfoxgroupId>
                <artifactId>springfox-boot-starterartifactId>
                <version>3.0.0version>
            dependency>
            
            <dependency>
                <groupId>com.github.xiaoymingroupId>
                <artifactId>swagger-bootstrap-uiartifactId>
                <version>1.9.6version>
            dependency>
            
            <dependency>
                <groupId>com.github.xiaoymingroupId>
                <artifactId>knife4j-spring-boot-starterartifactId>
                <version>3.0.3version>
            dependency>
            
            <dependency>
                <groupId>com.github.ulisesbocchiogroupId>
                <artifactId>jasypt-spring-boot-starterartifactId>
                <version>3.0.2version>
            dependency>
            
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>fastjsonartifactId>
                <scope>compilescope>
                <version>1.2.83_noneautotypeversion>
            dependency>
        dependencies>
    dependencyManagement>

    <build>
    build>

project>

gateway模块的pom.xml


<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.0modelVersion>
	<parent>
		<groupId>com.hippogroupId>
		<artifactId>java-studyartifactId>
		<version>0.0.1-SNAPSHOTversion>
		<relativePath>../pom.xmlrelativePath> 
	parent>

	<artifactId>study-gatewayartifactId>
	<name>${project.artifactId}name>
	<description>gateway网关description>

	<properties>
		<java.version>17java.version>
	properties>

	<dependencies>
		
		<dependency>
			<groupId>org.springframework.cloudgroupId>
			<artifactId>spring-cloud-starter-gatewayartifactId>
		dependency>
		
		<dependency>
			<groupId>com.alibaba.cloudgroupId>
			<artifactId>spring-cloud-starter-alibaba-nacos-configartifactId>
		dependency>
		
		<dependency>
			<groupId>com.alibaba.cloudgroupId>
			<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
		dependency>
		
		<dependency>
			<groupId>org.springframework.cloudgroupId>
			<artifactId>spring-cloud-starter-loadbalancerartifactId>
		dependency>
		
		<dependency>
			<groupId>org.springframework.cloudgroupId>
			<artifactId>spring-cloud-starter-bootstrapartifactId>
		dependency>
		
		<dependency>
			<groupId>org.projectlombokgroupId>
			<artifactId>lombokartifactId>
		dependency>
		
		<dependency>
			<groupId>cn.hutoolgroupId>
			<artifactId>hutool-coreartifactId>
		dependency>
	dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.bootgroupId>
				<artifactId>spring-boot-maven-pluginartifactId>
				<configuration>
					<mainClass>com.hippo.database.DataBaseApplicationmainClass>
					<skip>falseskip>
				configuration>
			plugin>
		plugins>
	build>

project>

2.1.2、修改启动类

添加注解@EnableDiscoveryClient

<?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.hippo</groupId>
		<artifactId>java-study</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath> <!-- lookup parent from repository -->
	</parent>

	<artifactId>study-gateway</artifactId>
	<name>${project.artifactId}</name>
	<description>gateway网关</description>

	<properties>
		<java.version>17</java.version>
	</properties>

	<dependencies>
		<!--  gateway  -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-gateway</artifactId>
		</dependency>
		<!-- Nacos配置中心依赖  -->
		<dependency>
			<groupId>com.alibaba.cloud</groupId>
			<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
		</dependency>
		<!-- Nacos 发现以进行服务注册/发现依赖  -->
		<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-loadbalancer</artifactId>
		</dependency>
		<!-- SpringCloud-2020.X.X以后版本官方重构了bootstrap引导配置的加载方式,需要添加以下依赖 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-bootstrap</artifactId>
		</dependency>
		<!-- lombok  -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<!-- hutools  -->
		<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-core</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<mainClass>com.hippo.database.DataBaseApplication</mainClass>
					<skip>false</skip>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

2.1.3、修改配置文件

注意:如果使用使用bootstrap.properties或者bootstrap.yaml,需要加入spring-cloud-starter-bootstrap依赖,这里使用bootstrap.yaml
当然你可以不使用bootstrap.yaml,你可以配置spring.config.import: optional:nacos:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}进行配置nacos需要导入的配置。

spring:
  application:
    name: gateway
  profiles:
    active: test
  host: 175.178.17.15
  cloud:
    nacos:
      discovery:
        server-addr: ${spring.host:127.0.0.1}:8848
        namespace: 29c504c4-0aa0-4a13-b487-5fddad0356f7
      config:
        serverAddr:  ${spring.host:127.0.0.1}:8848
        file-extension: yaml
        #        shared-configs: # 共享配置
        #            - dataId: gateway-dev.yaml
        #              group: DEFAULT_GROUP
        #              refresh: true
        namespace: 29c504c4-0aa0-4a13-b487-5fddad0356f7
    gateway:
      discovery:
        locator:
          enabled: true # 开启服务发现
      routes:
        - id: 数据操作 # 路由id
          uri: lb://database # 服务名
          predicates:
            - Path=/database/** # 路径匹配
          filters:
            - StripPrefix=1 # 去掉前缀

#  # 导入nacos配置
#  config:
#    # 因为springboot 2.4版本以后默认关闭加载bootstrap.yml,所以只能通过此方式连接到nacos config
#    import: optional:nacos:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}


management:
  endpoint:
    health:
      show-details: always
  endpoints:
    web:
      exposure:
        include: '*'
logging:
  level:
    com.alibaba.cloud.nacos.configdata: debug

2.1.4、nacos创建配置

nacos访问地址:http://XXX.XXX.XXX.XXX:8848/nacos

Data ID:gateway-test.yaml
Group:DEFAULT_GROUP
描述:xxxxx
配置格式:YAML
配置内容:

server: 
    port: 9000

spring: 
    cloud: 
        gateway: 
            discovery: 
                locator: 
                    enabled: true 
            # 路由配置        
            routes: 
                - id: 数据操作 
                  uri: lb://database 
                  predicates: 
                    - Path=/database/** 
                  filters: 
                    - StripPrefix=1 

发布

2.1.5、新增自定义路由配置类

新建RouteLocatorConfig

package com.hippo.studygateway.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName RouteLocatorConfig
 * @Description TODO 自定义网关路由配置
 * @Author tangxl
 * @create 2023-03-27 14:19
 **/
@Configuration
public class RouteLocatorConfig {

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder routeLocator){
        RouteLocatorBuilder.Builder routes = routeLocator.routes();
        return routes
                .route("path_route1", r -> r.path("/guonei")
                        .uri("http://news.baidu.com/guonei"))  //说明:访问localhost:9527/guonei地址会转发到http://news.baidu.com/guonei地址
                .route("path_route2",r->r.path("/guoji")
                        .uri("https://news.baidu.com/guoji"))
                .route("path_route3",r->r.path("/gateway")
                        .uri("https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/"))
                .route(p->
                        p.path("/lb/**") //lb: 请求地址中必须包含lb
                                .filters(f->f.stripPrefix(1)) //去掉第一个路径
                                .uri("lb://cloud-payment-service") //lb: 负载均衡指向地址
                )
                .build();
    }
}

2.1.6、新增打印日志过滤器

package com.hippo.studygateway.filter;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.LocalDate;
import java.util.Date;

/**
 * @ClassName GatewayLogFilter
 * @Description TODO 拦截日志类
 * @Author tangxl
 * @Date 2022/7/14 9:38
 **/
@Component
@Slf4j
public class LogGlobalFilter implements GlobalFilter, Ordered {
    //问题:无法注入Bean,需要手动将过滤器加载到容器中
//    @Autowired
//    private SystemFeignService systemFeignService;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("LogGlobalFilter日志记录:"+ DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
//        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
//        if (uname == null) {
//            log.info("************用户名为空!");
//            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
//            return exchange.getResponse().setComplete();
//        }

        String reqPath = exchange.getRequest().getPath().toString();
        String reqParams = exchange.getRequest().getQueryParams().toString();
        String reqBodys = exchange.getRequest().getBody().toString();
        log.info("请求路径:"+reqPath);
        log.info("params参数:"+reqParams);
        log.info("body参数:"+reqBodys);
//        systemFeignService.saveInterfaceLog("接口路径"+reqPath);
        return chain.filter(exchange);
    }

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

2.1.7、启动测试

浏览器输入:http://localhost:9000/database/config/get

显示:nacos-config-1.0

你可能感兴趣的:(#,gateway,gateway,java,spring,boot)