1、每次初始化安裝整套專案,包括安裝 Nacos 和其他服務還有mysql,redis等其他中介軟體,安裝後 Nacos 獲取不到 nacos 路由資訊(包括後續新寫入動態路由設定)!只有手動重啟 Nacos 服務後,才會生效,後續更新的動態路由設定也會正常;
<!--gateway-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- SpringCloud Ailibaba Nacos Config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
package com.cherf.flow.gateway.nacosconfig;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;
import javax.annotation.PostConstruct;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.cherf.flow.gateway.config.RoutesConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import reactor.core.publisher.Mono;
@Component
public class NacosDynamicRouteService implements ApplicationEventPublisherAware {
private static final Logger log = LoggerFactory.getLogger(NacosDynamicRouteService.class);
public static final long DEFAULT_TIMEOUT = 30000;
@Value("${spring.cloud.nacos.discovery.server-addr}")
private String serverAddr;
/**
* 設定 ID
*/
@Value("${flowGateway.dataId}")
private String dataId;
/**
* 設定 分組
*/
@Value("${flowGateway.group}")
private String group;
/**
* 靜態路由地址
*/
@Autowired
private RoutesConfig routesConfig;
@Autowired
private RouteDefinitionWriter routeDefinitionWriter;
private ApplicationEventPublisher applicationEventPublisher;
private static final List<String> ROUTE_LIST = new ArrayList<>();
// 增加閘道器啟動時,更新一次設定
@PostConstruct
public void init() {
log.info("gateway route init...");
try {
List<RouteDefinition> definitionList = new ArrayList<>();
definitionList.addAll(routesConfig.getRoutes());
Properties properties = new Properties();
// nacos伺服器地址,127.0.0.1:8848
properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
ConfigService configService = NacosFactory.createConfigService(properties);
if (configService != null) {
String configInfo = configService.getConfig(dataId, group, DEFAULT_TIMEOUT);
if (StringUtils.isNotBlank(configInfo)) {
definitionList.addAll(JSON.parseArray(configInfo, RouteDefinition.class));
}
}
log.info("update route : {}", definitionList);
for (RouteDefinition definition : definitionList) {
addRoute(definition);
}
} catch (Exception e) {
log.error("初始化閘道器路由時發生錯誤", e);
}
}
@PostConstruct
public void dynamicRouteByNacosListener() {
try {
Properties properties = new Properties();
// nacos伺服器地址,127.0.0.1:8848
properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
ConfigService configService = NacosFactory.createConfigService(properties);
if (configService != null) {
configService.getConfig(dataId, group, 5000);
configService.addListener(dataId, group, new Listener() {
@Override
public void receiveConfigInfo(String configInfo) {
if (StringUtils.isNotBlank(configInfo)) {
// 手動新設定以後,先清除原來的設定
clearRoute();
try {
List<RouteDefinition> gatewayRouteDefinitions = JSONObject.parseArray(configInfo, RouteDefinition.class);
gatewayRouteDefinitions.addAll(routesConfig.getRoutes());
for (RouteDefinition routeDefinition : gatewayRouteDefinitions) {
addRoute(routeDefinition);
}
publish();
} catch (Exception e) {
log.error("載入閘道器路由時發生錯誤", e);
}
}
}
@Override
public Executor getExecutor() {
return null;
}
});
}
} catch (NacosException e) {
log.error("載入閘道器路由時發生錯誤", e);
}
}
private void clearRoute() {
for (String id : ROUTE_LIST) {
this.routeDefinitionWriter.delete(Mono.just(id)).subscribe();
}
ROUTE_LIST.clear();
}
private void addRoute(RouteDefinition definition) {
try {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
ROUTE_LIST.add(definition.getId());
} catch (Exception e) {
log.error("初始化閘道器路由時發生錯誤", e);
}
}
private void publish() {
this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this.routeDefinitionWriter));
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}
package com.cherf.flow.gateway.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author
*/
@ConfigurationProperties(prefix = "spring.cloud.gateway")
@Data
@Component
public class RoutesConfig {
/**
* 所有的路由資訊
*/
private List<RouteDefinition> routes;
}
spring:
cloud:
nacos:
discovery:
# 不使用nacos的設定
# enabled: false
server-addr: NACOS_HOST
config:
# 設定中心地址
server-addr: NACOS_HOST
# 組態檔格式
file-extension: yml
username:
password:
gateway:
discovery:
locator:
enabled: true #開啟從註冊中心動態建立路由的功能,利用微服務名進行路由
routes:
- id: i-console-api #payment_route #路由的ID,沒有固定規則但要求唯一,建議配合服務名
uri: lb://i-console-api #匹配後提供服務的路由地址,lb為負載均衡的其中一種模式
predicates:
# 斷言,路徑相匹配的進行路由
- Path= /api/**,/oapi/**
filters: #redis令牌桶限流功能
- name: RequestRateLimiter
args:
# 令牌桶每秒填充平均速率
redis-rate-limiter.replenishRate: 100
# 令牌桶的總容量
redis-rate-limiter.burstCapacity: 100
- id: i-system-api #payment_route #路由的ID,沒有固定規則但要求唯一,建議配合服務名
uri: lb://i-system-api #匹配後提供服務的路由地址,lb為負載均衡的其中一種模式
predicates:
# 斷言,路徑相匹配的進行路由
- Path= /sys/**,/user/**
filters: #redis令牌桶限流功能
- name: RequestRateLimiter
args:
# 令牌桶每秒填充平均速率
redis-rate-limiter.replenishRate: 100
# 令牌桶的總容量
redis-rate-limiter.burstCapacity: 100
flowGateway:
dataId: gateway-flow
group: DEFAULT_GROUP
新增設定
路由資訊
** 在啟動類中需要新增註解@EeableDiscoveryClient**
package com.cherf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
@EnableDiscoveryClient
public class FlowGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(FlowGatewayApplication.class, args);
}
}
組態檔不生效的把名字改為bootstrap.yml
仔細看 Data Id 和 Group 設定;
yml 中設定是否開啟了;
還有很多可能的原因可以看官方issue去解決
這些都不符合我的情況!
後續發現是安裝後只有第一次自動更新設定有問題,重啟Nacos後消失,不是一直有問題,所以就從nacos重新整理設定的程式碼下手,最終定位問題出在時區上;
使用 show VARIABLES like '%time_zone%';
檢視資料庫時區;
/nacos/conf/
目錄下 application.properties
中資料來源 url 的時區為 UTC 和資料庫不一致導致
將 nacos 組態檔中的 serverTimezone=UTC
改成 serverTimezone=Asia/Shanghai
後解決!
解決了我的問題,但是也可能不適用於其他場景!歡迎大家討論!