Gateway的使用

怀飞扬
2023-12-01

父工程

<?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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xysd.cloud</groupId>
    <artifactId>cloudexecise2</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>cloudproviderproduct</module>
        <module>clouderureka</module>
        <module>cloudgateway</module>
    </modules>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>


    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <finalName>cloudexecise2</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${java.version}</source><!-- 源代码使用的开发版本 -->
                    <target>${java.version}</target><!-- 需要生成的目标class文件的编译版本 -->
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

生产者cloudproviderproduct

<?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>cloudexecise2</artifactId>
        <groupId>com.xysd.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-provider-product</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>com.xysd.cloud</groupId>
            <artifactId>cloud-api</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.31</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    <!--健康信息监控-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

    </dependencies>

    <build>
        <finalName>cloud-eureka</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <delimiters>
                        <delimiter>$</delimiter>
                    </delimiters>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${java.version}</source><!-- 源代码使用的开发版本 -->
                    <target>${java.version}</target><!-- 需要生成的目标class文件的编译版本 -->
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

配置

server:
 port: 8080
mybatis:  #mybatyis的配置
  mapper-locations: classpath:mapper/*.xml
spring:
 datasource:
   type: com.alibaba.druid.pool.DruidDataSource # 配置当前要使用的数据源的操作类型
   driver-class-name: com.mysql.cj.jdbc.Driver # 配置MySQL的驱动程序类
   url: jdbc:mysql://localhost:3306/cloud?serverTimezone=GMT%2B8 # 数据库连接地址
   username: root # 数据库用户名
   password: root # 数据库连接密码
 application:
   name: cloudproviderproduct
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    instance-id: cloudproviderproduct
    prefer-ip-address: true #显示ip
info:
  app.name: cloudproviderproduct
  company.name: xysd
  build.artifactId: $project.artifactId$
  build.modelVersion: $project.modelVersion$

代码

import com.xysd.cloud.entity.Product;

import java.util.List;

public interface ProductMapper {
    boolean create(Product product);
    public Product findById(Long id);
    public List<Product> findAll();
}

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xysd.cloud.mapper.ProductMapper">

    <resultMap id="productResult" type="com.xysd.cloud.entity.Product">
        <id column="productId" property="productId"/>
        <result column="productName" property="productName"/>
        <result column="productDesc" property="productDesc"/>
    </resultMap>
    <select id="findById" resultMap="productResult" parameterType="long">
        select productId,productName,productDesc from product WHERE productId=#{id} ;
    </select>
    <select id="findAll" resultMap="productResult">
        SELECT productId,productName,productDesc from product;
    </select>
    <insert id="create" parameterType="com.xysd.cloud.entity.Product">
        INSERT INTO product(productName,productDesc) VALUES (#{productName},database()) ;
    </insert>
</mapper>
package com.xysd.cloud.service;

import com.xysd.cloud.entity.Product;

import java.util.List;

public interface ProductService {
    Product get(long id);
    boolean add(Product product);
    List<Product> list();
}

package com.xysd.cloud.service.impl;

import com.xysd.cloud.entity.Product;
import com.xysd.cloud.mapper.ProductMapper;
import com.xysd.cloud.service.ProductService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductMapper productMapper;

    @Override
    public Product get(long id) {
        return productMapper.findById(id);
    }

    @Override
    public boolean add(Product product) {
        System.out.println(product);
        return productMapper.create(product);
    }

    @Override
    public List<Product> list() {
        return productMapper.findAll();
    }
}

package com.xysd.cloud.controller;

import com.xysd.cloud.entity.Product;
import com.xysd.cloud.service.ProductService;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

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

    @Resource
    private ProductService productService;

    @RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
    public Object get(@PathVariable("id") long id) {
        return this.productService.get(id);
    }

    @RequestMapping(value = "/add")
    public Object add(@RequestBody Product product) {
        return this.productService.add(product);
    }

    @RequestMapping(value = "/list")
    public Object list() {
        return this.productService.list();
    }
}
package com.xysd.cloud;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableEurekaClient
@SpringBootApplication
@MapperScan("com.xysd.cloud.mapper")
public class ProductApp {
    public static void main(String[] args) {
        SpringApplication.run(ProductApp.class,args);
    }
}

注册中心cloudeureka

依赖

<?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>cloudexecise2</artifactId>
        <groupId>com.xysd.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-erureka</artifactId>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>

    <build>
        <finalName>eureka-server</finalName>
        <plugins>
            <plugin> <!-- 该插件的主要功能是进行项目的打包发布处理 -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration> <!-- 设置程序执行的主类 -->
                    <mainClass>com.xysd.cloud.EurekaApp</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

配置application.yml


server:
  port: 8761
eureka:
  instance:
    hostname: localhost   # 定义 Eureka 实例所在的主机名称
  client:
    fetch-registry: false #是否从eureka中获取注册信息
    register-with-eureka: false #是否将自己注册到注册中心
    service-url:
      defaultZone: http://localhost:8761/eureka/

代码

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaApp {

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

服务网关Gateway(cloudgateway)

<?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>cloudexecise2</artifactId>
        <groupId>com.xysd.cloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloudgateway</artifactId>

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

</project>

配置

server:
  port: 8085
spring:
  application:
    name: cloudgateway
  cloud:
    gateway:
      routes:
        - id: cloudproviderproduct #服务应用名称 保持唯一
          uri: lb://service-product #lb://根据微服务名称从注册中心拉取服务请求路径 #http://localhost:8080 #目标服务请求地址
          predicates:
            - Path=/cloudproviderproduct/** #断言,也就是路由条件  路径匹配原则
          filters:  # #配置路由过滤器   可以将请求http://127.0.0.1:8080/cloudproviderproduct/product/get/1    --->变成http://127.0.0.1:8080/cloudproviderproduct/product/get/1
            - RewritePath=/cloudproviderproduct/(?<segment>.*), /$\{segment} # 正则表达式   重写转发路径,将cloudproviderproduct去掉, $在yml中写法为$\,需要转义
      discovery:
        locator:
          enabled: true  #开启根据微服务名称转发
          lower-case-service-id: true  #微服务名称已小写形式呈现
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true #使用ip地址注册
    instance-id: cloudgateway
package com.xysd.cloud;

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

@EnableDiscoveryClient
@SpringBootApplication
public class GatewayApplication {

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

测试

http://localhost:8085/cloudproviderproduct/product/list

过滤器

package com.xysd.cloud.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class LoginFilter implements GlobalFilter,Ordered {

    @Override
    /**
     * 执行过滤器中的业务逻辑
     *     对请求参数中的access-token进行判断
     *      如果存在此参数:代表已经认证成功
     *      如果不存在此参数 : 认证失败.
     *  ServerWebExchange : 相当于请求和响应的上下文(zuul中的RequestContext)
     */
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("执行了自定义的过滤器");
        //1.获取请求参数access-token
        String token = exchange.getRequest().getQueryParams().getFirst("access-token");
        //2.判断是否存在
        if(token == null) {
            //3.如果不存在 : 认证失败
            System.out.println("没有登录");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);//未认证
            return exchange.getResponse().setComplete(); //请求结束
        }
        //4.如果存在,继续执行
        return chain.filter(exchange); //继续向下执行
    }

    @Override
    /**
     * 指定过滤器的执行顺序,返回值越小,执行的优先级越高
     */
    public int getOrder() {
        return 0;
    }


}

测试

http://localhost:8085/cloudproviderproduct/product/list?access-token=1,必须带上这个参数,否则401

 类似资料: