自定义RouteDefinitionLocator@Slf4j
@Component
public class NcosRouteDefinitionLocator implements RouteDefinitionLocator, InitializingBean {
private volatile List<RouteDefinition> routeDefinitions = new CopyOnWriteArrayList<>() ;
@Autowired
private NacosConfigManager nacosConfigManager ;
@Autowired
private ObjectMapper objectMapper ;
@Autowired
private ApplicationEventPublisher eventPublisher ;
private ConfigService configService ;
@Override
public Flux<RouteDefinition> getRouteDefinitions() {
return Flux.fromIterable(routeDefinitions);
}
@Override
public void afterPropertiesSet() throws Exception {
configService = nacosConfigManager.getConfigService();
this.initNacosConfig();
this.initNacosListener();
}
private void initNacosConfig(){
try {
String content = configService.getConfig(
NacosConfig.DATA_ID,
NacosConfig.GROUP_ID,
3000L
);
CollectionType collectionType = objectMapper.getTypeFactory()
.constructCollectionType(ArrayList.class, RouteDefinition.class);
routeDefinitions = objectMapper.readValue(content, collectionType);
}catch (NacosException e){
log.info("nacos config NacosException ", e);
} catch (JsonProcessingException e) {
log.info("nacos config JsonProcessingException ", e);
}
}
private void initNacosListener() throws NacosException {
configService.addListener(
NacosConfig.DATA_ID,
NacosConfig.GROUP_ID,
new DataChangeListener());
}
class DataChangeListener implements Listener{
@Override
public Executor getExecutor() {
return null;
}
@Override
public void receiveConfigInfo(String content) {
try {
log.info("gateway config change : {}", content);
CollectionType collectionType = objectMapper.getTypeFactory()
.constructCollectionType(ArrayList.class, RouteDefinition.class);
routeDefinitions = objectMapper.readValue(content, collectionType);
eventPublisher.publishEvent(new RefreshRoutesEvent(content));
}catch (JsonProcessingException e) {
log.info("nacos config JsonProcessingException ", e);
}
}
}
}

- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67