Nacos数据同步源码分析
Apache ShenYu 是一个异步的,高性能的,跨语言的,响应式的
API网关 。
在ShenYu网关中,数据同步是指,当在后台管理系统中,数据发送了更新后,如何将更新的数据同步到网关中。Apache ShenYu 网关当前支持ZooKeeper、WebSocket、Http长轮询、Nacos 、Etcd 和 Consul 进行数据同步。本文的主要内容是基于Nacos的数据同步源码分析。
本文基于
shenyu-2.4.0版本进行源码分析,官网的介绍请参考 数据同步原理 。
1. 关于Nacos
Nacos 平台用于动态服务发现,以及配置和服务管理。 Shenyu网关可选择使用Nacos进行数据同步。
2. Admin数据同步
我们从一个实际案例进行源码追踪,比如在后台管理系统中,对Divide插件中的一条选择器数据进行更新,将权重更新为90:

2.1 接收数据
- SelectorController.updateSelector()
进入SelectorController类中的updateSelector()方法,它负责数据的校验,添加或更新数据,返回结果信息。
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/selector")
public class SelectorController {
@PutMapping("/{id}")
public ShenyuAdminResult updateSelector(@PathVariable("id") final String id, @Valid @RequestBody final SelectorDTO selectorDTO) {
// 设置当前选择器数据id
selectorDTO.setId(id);
// 创建或更新操作
Integer updateCount = selectorService.createOrUpdate(selectorDTO);
// 返回结果信息
return ShenyuAdminResult.success(ShenyuResultMessage.UPDATE_SUCCESS, updateCount);
}
// ......
}
2.2 处理数据
- SelectorServiceImpl.createOrUpdate()
在SelectorServiceImpl类中通过createOrUpdate()方法完成数据的转换,保存到数据库,发布事件,更新upstream。
@RequiredArgsConstructor
@Service
public class SelectorServiceImpl implements SelectorService {
// 负责事件发布的eventPublisher
private final ApplicationEventPublisher eventPublisher;
@Override
@Transactional(rollbackFor = Exception.class)
public int createOrUpdate(final SelectorDTO selectorDTO) {
int selectorCount;
// 构建数据 DTO --> DO
SelectorDO selectorDO = SelectorDO.buildSelectorDO(selectorDTO);
List<SelectorConditionDTO> selectorConditionDTOs = selectorDTO.getSelectorConditions();
// 判断是添加还是更新
if (StringUtils.isEmpty(selectorDTO.getId())) {
// 插入选择器数据
selectorCount = selectorMapper.insertSelective(selectorDO);
// 插入选择器中的条件数据
selectorConditionDTOs.forEach(selectorConditionDTO -> {
selectorConditionDTO.setSelectorId(selectorDO.getId());
selectorConditionMapper.insertSelective(SelectorConditionDO.buildSelectorConditionDO(selectorConditionDTO));
});
// check selector add
// 权限检查
if (dataPermissionMapper.listByUserId(JwtUtils.getUserInfo().getUserId()).size() > 0) {
DataPermissionDTO dataPermissionDTO = new DataPermissionDTO();
dataPermissionDTO.setUserId(JwtUtils.getUserInfo().getUserId());
dataPermissionDTO.setDataId(selectorDO.getId());
dataPermissionDTO.setDataType(AdminConstants.SELECTOR_DATA_TYPE);
dataPermissionMapper.insertSelective(DataPermissionDO.buildPermissionDO(dataPermissionDTO));
}
} else {
// 更新数据,先删除再新增
selectorCount = selectorMapper.updateSelective(selectorDO);
//delete rule condition then add
selectorConditionMapper.deleteByQuery(new SelectorConditionQuery(selectorDO.getId()));
selectorConditionDTOs.forEach(selectorConditionDTO -> {
selectorConditionDTO.setSelectorId(selectorDO.getId());
SelectorConditionDO selectorConditionDO = SelectorConditionDO.buildSelectorConditionDO(selectorConditionDTO);
selectorConditionMapper.insertSelective(selectorConditionDO);
});
}
// 发布事件
publishEvent(selectorDO, selectorConditionDTOs);
// 更 新upstream
updateDivideUpstream(selectorDO);
return selectorCount;
}
// ......
}
在Service类完成数据的持久化操作,即保存数据到数据库,这个比较简单,就不深入追踪了。关于更新upstream操作,放到后面对应的章节中进行分析,重点关注发布事件的操作,它会执行数据同步。
publishEvent()方法的逻辑是:找到选择器对应的插件,构建条件数据,发布变更数据。
private void publishEvent(final SelectorDO selectorDO, final List<SelectorConditionDTO> selectorConditionDTOs) {
// 找到选择器对应的插件
PluginDO pluginDO = pluginMapper.selectById(selectorDO.getPluginId());
// 构建条件数据
List<ConditionData> conditionDataList = selectorConditionDTOs.stream().map(ConditionTransfer.INSTANCE::mapToSelectorDTO).collect(Collectors.toList());
// 发布变更数据
eventPublisher.publishEvent(new DataChangedEvent(ConfigGroupEnum.SELECTOR, DataEventTypeEnum.UPDATE,
Collections.singletonList(SelectorDO.transFrom(selectorDO, pluginDO.getName(), conditionDataList))));
}
发布变更数据通过eventPublisher.publishEvent()完成,这个eventPublisher对象是一个ApplicationEventPublisher类,这个类的全限定名是org.springframework.context.ApplicationEventPublisher。看到这儿,我们知道了发布数据是通过Spring相关的功能来完成的。
关于
ApplicationEventPublisher:当有状态发生变化时,发布者调用
ApplicationEventPublisher的publishEvent方法发布一个事件,Spring容器广播事件给所有观察者,调用观察者的onApplicationEvent方法把事件对象传递给观察者。调用publishEvent方法有两种途径,一种是实现接口由容器注入ApplicationEventPublisher对象然后调用其方法,另一种是直接调用 容器的方法,两种方法发布事件没有太大区别。
ApplicationEventPublisher:发布事件;ApplicationEvent:Spring事件,记录事件源、时间和数据;ApplicationListener:事件监听者,观察者;
在Spring的事件发布机制中,有三个对象,
一个是发布事件的ApplicationEventPublisher,在ShenYu中通过构造器注入了一个eventPublisher。
另一个对象是ApplicationEvent,在ShenYu中通过DataChangedEvent继承了它,表示事件对象。
public class DataChangedEvent extends ApplicationEvent {
//......
}
最后一个是 ApplicationListener,在ShenYu中通过DataChangedEventDispatcher类实现了该接口,作为事件的监听者,负责处理事件对象。
@Component
public class DataChangedEventDispatcher implements ApplicationListener<DataChangedEvent>, InitializingBean {
//......
}
2.3 分发数据
- DataChangedEventDispatcher.onApplicationEvent()
当事件发布完成后,会自动进入到DataChangedEventDispatcher类中的onApplicationEvent()方法,进行事件处理。
@Component
public class DataChangedEventDispatcher implements ApplicationListener<DataChangedEvent>, InitializingBean {
/**
* 有数据变更时,调用此方法
* @param event
*/
@Override
@SuppressWarnings("unchecked")
public void onApplicationEvent(final DataChangedEvent event) {
// 遍历数据变更监听器(一般使用一种数据同步的方式就好了)
for (DataChangedListener listener : listeners) {
// 哪种数据发生变更
switch (event.getGroupKey()) {
case APP_AUTH: // 认证信息
listener.onAppAuthChanged((List<AppAuthData>) event.getSource(), event.getEventType());
break;
case PLUGIN: // 插件信息
listener.onPluginChanged((List<PluginData>) event.getSource(), event.getEventType());
break;
case RULE: // 规则信息
listener.onRuleChanged((List<RuleData>) event.getSource(), event.getEventType());
break;
case SELECTOR: // 选择器信息
listener.onSelectorChanged((List<SelectorData>) event.getSource(), event.getEventType());
break;
case META_DATA: // 元数据
listener.onMetaDataChanged((List<MetaData>) event.getSource(), event.getEventType());
break;
default: // 其他类型,抛出异常
throw new IllegalStateException("Unexpected value: " + event.getGroupKey());
}
}
}
}
当有数据变更时,调用onApplicationEvent方法,然后遍历所有数据变更监听器,判断是哪种数据类型,交给相应的数据监听器进行处理。
ShenYu将所有数据进行了分组,一共是五种:认证信息、插件信息、规则信息、选择器信息和元数据。
这里的数据变更监听器(DataChangedListener),就是数据同步策略的抽象,它的具体实现有:

这几个实现类就是当前ShenYu支持的同步策略:
WebsocketDataChangedListener:基于websocket的数据同步;ZookeeperDataChangedListener:基于zookeeper的数据同步;ConsulDataChangedListener:基于consul的数据同步;EtcdDataDataChangedListener:基于etcd的数据同步;HttpLongPollingDataChangedListener:基于http长轮询的数据同步;NacosDataChangedListener:基于nacos的数据同步;
既然有这么多种实现策略,那么如何确定使用哪一种呢?
因为本文是基于Nacos的数据同步源码分析,所以这里以NacosDataChangedListener为例,分析它是如何被加载并实现的。
通过查看对NacosDataChangedListener类的调用,可以发现,它是在DataSyncConfiguration类进行配置的。
/**
* 数据同步配置类
* 通过springboot条件装配实现
* The type Data sync configuration.
*/
@Configuration
public class DataSyncConfiguration {
//省略了其他代码......
/**
* The type Nacos listener.
*/
@Configuration
@ConditionalOnProperty(prefix = "shenyu.sync.nacos", name = "url")
@Import(NacosConfiguration.class)
static class NacosListener {
/**
* Data changed listener data changed listener.
*
* @param configService the config service
* @return the data changed listener
*/
@Bean
@ConditionalOnMissingBean(NacosDataChangedListener.class)
public DataChangedListener nacosDataChangedListener(final ConfigService configService) {
return new NacosDataChangedListener(configService);
}
/**
* Nacos data init zookeeper data init.
*
* @param configService the config service
* @param syncDataService the sync data service
* @return the nacos data init
*/
@Bean
@ConditionalOnMissingBean(NacosDataInit.class)
public NacosDataInit nacosDataInit(final ConfigService configService, final SyncDataService syncDataService) {
return new NacosDataInit(configService, syncDataService);
}
}
//省略了其他代码......
}
这个配置类是通过SpringBoot条件装配类实现的。在NacosListener类上面有几个注解:
-
@Configuration:配置文件,应用上下文; -
@ConditionalOnProperty(prefix = "shenyu.sync.nacos", name = "url"):属性条件判断,满足条件,该配置类才会生效。也就是说,当我们有如下配置时,就会采用nacos进行数据同步。shenyu:
sync:
nacos:
url: localhost:8848 -
@Import(NacosConfiguration.class):导入另一个配置类NacosConfiguration,NacosConfiguration提供了一个方法ConfigService nacosConfigService(final NacosProperties nacosProp),将Nacos属性转换为ConfigService类型的bean,而Nacos属性是通过@EnableConfigurationProperties(NacosProperties.class)导入的。我们先看ConfigService类型的bean定义。再分析属性配置类和对应的属性配置文件。
/**
* Nacos configuration.
*/
@EnableConfigurationProperties(NacosProperties.class)
public class NacosConfiguration {
/**
* register configService in spring ioc.
*
* @param nacosProp the nacos configuration
* @return ConfigService {@linkplain ConfigService}
* @throws Exception the exception
*/
@Bean
@ConditionalOnMissingBean(ConfigService.class)
public ConfigService nacosConfigService(final NacosProperties nacosProp) throws Exception {
Properties properties = new Properties();
if (nacosProp.getAcm() != null && nacosProp.getAcm().isEnabled()) {
// Use aliyun ACM service
properties.put(PropertyKeyConst.ENDPOINT, nacosProp.getAcm().getEndpoint());
properties.put(PropertyKeyConst.NAMESPACE, nacosProp.getAcm().getNamespace());
// Use subaccount ACM administrative authority
properties.put(PropertyKeyConst.ACCESS_KEY, nacosProp.getAcm().getAccessKey());
properties.put(PropertyKeyConst.SECRET_KEY, nacosProp.getAcm().getSecretKey());
} else {
properties.put(PropertyKeyConst.SERVER_ADDR, nacosProp.getUrl());
if (StringUtils.isNotBlank(nacosProp.getNamespace())) {
properties.put(PropertyKeyConst.NAMESPACE, nacosProp.getNamespace());
}
if (StringUtils.isNotBlank(nacosProp.getUsername())) {
properties.put(PropertyKeyConst.USERNAME, nacosProp.getUsername());
}
if (StringUtils.isNotBlank(nacosProp.getPassword())) {
properties.put(PropertyKeyConst.PASSWORD, nacosProp.getPassword());
}
}
return NacosFactory.createConfigService(properties);
}
}
这个方法主要分成两步,第一步根据是否使用了aliyun的ACM服务,从NacosProperties中获取不同的nacos路径和鉴权信息,第二步根据获取到的这些属性,使用Nacos官方的工厂方法,使用反射的方式,创建configService。
接下来,让我们分析一下Nacos的属性配置和对应的配置文件。
/**
* The type Nacos config.
*/
@ConfigurationProperties(prefix = "shenyu.sync.nacos")
public class NacosProperties {
private String url;
private String namespace;
private String username;
private String password;
private NacosACMProperties acm;
/**
* Gets the value of url.
*
* @return the value of url
*/
public String getUrl() {
return url;
}
/**
* Sets the url.
*
* @param url url
*/
public void setUrl(final String url) {
this.url = url;
}
/**
* Gets the value of namespace.
*
* @return the value of namespace
*/
public String getNamespace() {
return namespace;
}
/**
* Sets the namespace.
*
* @param namespace namespace
*/
public void setNamespace(final String namespace) {
this.namespace = namespace;
}
/**
* Gets the value of username.
*
* @return the value of username
*/
public String getUsername() {
return username;
}
/**
* Sets the username.
*
* @param username username
*/
public void setUsername(final String username) {
this.username = username;
}
/**
* Gets the value of password.
*
* @return the value of password
*/
public String getPassword() {
return password;
}
/**
* Sets the password.
*
* @param password password
*/
public void setPassword(final String password) {
this.password = password;
}
/**
* Gets the value of acm.
*
* @return the value of acm
*/
public NacosACMProperties getAcm() {
return acm;
}
/**
* Sets the acm.
*
* @param acm acm
*/
public void setAcm(final NacosACMProperties acm) {
this.acm = acm;
}
public static class NacosACMProperties {
private boolean enabled;
private String endpoint;
private String namespace;
private String accessKey;
private String secretKey;
/**
* Gets the value of enabled.
*
* @return the value of enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* Sets the enabled.
*
* @param enabled enabled
*/
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
/**
* Gets the value of endpoint.
*
* @return the value of endpoint
*/
public String getEndpoint() {
return endpoint;
}
/**
* Sets the endpoint.
*
* @param endpoint endpoint
*/
public void setEndpoint(final String endpoint) {
this.endpoint = endpoint;
}
/**
* Gets the value of namespace.
*
* @return the value of namespace
*/
public String getNamespace() {
return namespace;
}
/**
* Sets the namespace.
*
* @param namespace namespace
*/
public void setNamespace(final String namespace) {
this.namespace = namespace;
}
/**
* Gets the value of accessKey.
*
* @return the value of accessKey
*/
public String getAccessKey() {
return accessKey;
}
/**
* Sets the accessKey.
*
* @param accessKey accessKey
*/
public void setAccessKey(final String accessKey) {
this.accessKey = accessKey;
}
/**
* Gets the value of secretKey.
*
* @return the value of secretKey
*/
public String getSecretKey() {
return secretKey;
}
/**
* Sets the secretKey.
*
* @param secretKey secretKey
*/
public void setSecretKey(final String secretKey) {
this.secretKey = secretKey;
}
}
}
当我们在配置文件中配置了shenyu.sync.nacos.url属性时,将采用nacos进行数据同步,此时配置类NacosListener会生效,并生成NacosDataChangedListener和NacosDataInit类型的bean。
- 生成
NacosDataChangedListener类型的bean,nacosDataChangedListener,这个bean将ConfigService类型的bean作为成员变量,ConfigService