【Spring Cloud、Gateway】搭建Spirng Cloud项目(四):Spring Cloud搭建Gateway服务

一、环境准备

1、Nacos已经搭建。参考链接
2、被管理的服务整合Nacos成功。参考链接

二、Spring Cloud搭建Gateway服务

1、引入依赖

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

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

2、bootstrap.yml配置

server:
  port: 7777

spring:
  application:
    name: gateway-server
  profiles:
    active: dev
  cloud:
    nacos:
      discovery:
        server-addr: pfhe.com:7001
        namespace: ${spring.profiles.active}
        group: TEST_GROUP
        username: nacos
        password: nacos
    gateway:
      routes:
          # 唯一ID
        - id: a-server
          # 对应服务:写法一(lb://a-server)、写法二(http://localhost:7100/)
          uri: lb://a-server
          # 断言
          predicates:
            - Path=/a/**
          # 过滤
          filters:
            - StripPrefix=1

3、启动类

package com.test.gateway;


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

/**
 * @author He PanFu
 * @date 2022-03-07 15:14:43
 */
@EnableDiscoveryClient
@SpringBootApplication
public class GatewayServerApplication {

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

三、问题总结

1、报错:Consider defining a bean of type ‘org.springframework.http.codec.ServerCodecConfigurer’ in your configuration.

解决方法一:网关的pom依赖中不能包含spring-boot-starter-web,不然会存在冲突。在其他服务中添加spring-boot-starter-web依赖就好了。(成功)
解决方法二:spring-cloud-starter-gateway依赖中排除spring-boot-starter-web。(可能还是失败)

 <!-- spring-cloud网关-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-web</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

四、拓展

1、Gateway断言和过滤器相关文章推荐

Gateway内置的路由断言工厂
Gateway之自定义路由断言工厂
Gateway之过滤器

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值