放弃幻想,认清现实,准备斗争
在srb下创建普通maven模块
- <dependencies>
-
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-gatewayartifactId>
- dependency>
-
- <dependency>
- <groupId>com.alibaba.cloudgroupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
- dependency>
- dependencies>
- server:
- port: 80 # 服务端口
-
- spring:
- profiles:
- active: dev # 环境设置
- application:
- name: service-gateway # 服务名
- cloud:
- nacos:
- discovery:
- server-addr: localhost:8848 # nacos服务地址
- gateway:
- discovery:
- locator:
- enabled: true # gateway可以发现nacos中的微服务,并自动生成转发路由
修改日志输出目录名为 gateway
-
- @SpringBootApplication
- @EnableDiscoveryClient
- public class ServiceGatewayApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(ServiceGatewayApplication.class, args);
- }
- }
nginx.exe -s stop
application.yml文件中添加路由配置
- #spring:
- # cloud:
- # gateway:
- routes:
- - id: service-core
- uri: lb://service-core
- predicates:
- - Path=/*/core/**
- - id: service-sms
- uri: lb://service-sms
- predicates:
- - Path=/*/sms/**
- - id: service-oss
- uri: lb://service-oss
- predicates:
- - Path=/*/oss/**
在 api-gateway中添加跨域配置
- @Configuration
- public class CorsConfig {
- @Bean
- public CorsWebFilter corsFilter() {
- CorsConfiguration config = new CorsConfiguration();
- config.setAllowCredentials(true); //是否允许携带cookie
- config.addAllowedOrigin("*"); //可接受的域,是一个具体域名或者*(代表任意域名)
- config.addAllowedHeader("*"); //允许携带的头
- config.addAllowedMethod("*"); //允许访问的方式
-
- UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
- source.registerCorsConfiguration("/**", config);
-
- return new CorsWebFilter(source);
- }
- }
删除微服务中的跨域注解 @CrossOrigin
failed to req API:localhost:8848/nacos/v1/ns/instance. code:500 msg: java.net.ConnectException
解决
1、检查nacos有没有开启
2、检查nacos开启是否正常
3、nacos和eureka不一样,eureka是项目的一部分,nacos更像是合作伙伴的关系,新手容易忽略
如果nacos正常开启了,重新启动项目,还是不行
(1)检查注解@EnableDiscoveryClient
(2)检查配置文件