Skip to content

gateway使用

This page demonstrates some of the built-in markdown extensions provided by VitePress.

gateway使用

pom.xml

md
```xml
<!-- nacos服务注册发现依赖 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- nacos配置中心依赖 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!-- 网关gateway依赖 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- 当前版本需要覆盖spring-web,不然每次上传文件都会新建一个临时目录 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.2.16.RELEASE</version>
</dependency>
```

MainClass

md
```java
@EnableDiscoveryClient // 开启服务注册和发现
@SpringBootApplication
@RefreshScope
public class ConcareGatewayApplication {
    
    public static void main( String[] args ) {
        IdGeneratorOptions options = new IdGeneratorOptions();
        options.WorkerId = 3;//机器编码
        YitIdHelper.setIdGenerator(options);
        SpringApplication.run(ConcareGatewayApplication.class, args);
    }
}
```

bootstrap.yml

md
```yml
server:
  port: 7827
  tomcat:
    max-http-form-post-size: 100MB

spring:
  application:
    name: gateway
  profiles:
    # 指定激活环境
    active: local
    # 包括 routes 配置
    include: routes
  cloud:
    gateway:
        filter:
            hystrix:
                enabled: false
        httpclient:
            websocket:
                max-frame-payload-length: 104857600
    nacos:
        # 注册中心
        discovery:
            server-addr: ${concare.nacos-addr}
        # 配置中心
        config:
            server-addr: ${concare.nacos-addr}
            # 指定 配置文件后缀
            file-extension: yaml
            # Nacos 上配置文件的 dataId,默认是服务名称
        username: nacos
        password: nacos

```

routes

md
```yml
spring:
  cloud:
    gateway:
      # 路由
      routes:
        # 路由 id
        - id: uims
          # lb,指定从 Nacos 中负载均衡拉取服务
          uri: lb://uims
          # 断言
          predicates:
            - Path=/uims/**
          filters:
            - StripPrefix=1
```

自定义路由规则

自定义路由规则用于开发环境下多人同时开发同一个应用时,跟不同的前端联调的时候需要固定服务
DebugLoadBalance

md
```java
@Slf4j
public class DebugLoadBalance extends RoundRobinRule {


    @Override
    public Server choose(Object o) {
        String destination = (String) RuleThreadLocal.get();
        RuleThreadLocal.remove();
        if (StringUtils.isEmpty(destination)){
            return super.choose(o);
        }
        List<Server> servers = this.getLoadBalancer().getReachableServers();
        if (CollectionUtil.isEmpty(servers)){
            return super.choose(o);
        }
        for (Server server : servers) {
            String hostPort = server.getHostPort();
            if (destination.equalsIgnoreCase(hostPort)){
                log.info("访问前端指定的目标地址:{}",hostPort);
                return server;
            }
        }
        return super.choose(o);
    }
}
```

DefaultRibbonConfig

md
```java 
@Configuration
@RibbonClients(
        value = {
                @RibbonClient(name = "gatewayRule", configuration = DebugLoadBalance.class),
        },
        defaultConfiguration = DefaultRibbonConfig.class)
public class DefaultRibbonConfig {

    @Bean
    public IRule ribbonRule() {
        return new DebugLoadBalance();
    }
}
```

RuleThreadLocal

md
```java 
/**
 * fei请求线程变量,需要在过滤器通过set方法添加目标服务ip和端口号
 */
public class RuleThreadLocal {

    public static final String KEY = "destination";

    /**
     * 异步处理业务时需要此线程变量传输数据
     */
    private final static ThreadLocal threadLocal = new ThreadLocal();

    public static Object get(){
        return threadLocal.get();
    }

    public static void  set(Object args){
        if (args == null){
            return;
        }
        threadLocal.set(args);
    }

    public static void remove(){
        threadLocal.remove();
    }
}
```

More

Check out the documentation for the full list of markdown extensions.