一、环境准备
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>