Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: https://github.com/ctripcorp/apollo/issues/2111 #2226

Closed
wants to merge 4 commits into from
Closed
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,6 @@
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
Expand All @@ -45,13 +34,24 @@
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

/**
* @author Jason Song([email protected])
*/
@RestController
@RequestMapping("/notifications/v2")
public class NotificationControllerV2 implements ReleaseMessageListener {

private static final Logger logger = LoggerFactory.getLogger(NotificationControllerV2.class);
private final Multimap<String, DeferredResultWrapper> deferredResults =
Multimaps.synchronizedSetMultimap(HashMultimap.create());
Expand All @@ -78,8 +78,9 @@ public NotificationControllerV2(
final NamespaceUtil namespaceUtil,
final Gson gson,
final BizConfig bizConfig) {
largeNotificationBatchExecutorService = Executors.newSingleThreadExecutor(ApolloThreadFactory.create
("NotificationControllerV2", true));
largeNotificationBatchExecutorService = Executors
.newSingleThreadExecutor(ApolloThreadFactory.create
("NotificationControllerV2", true));
this.watchKeysUtil = watchKeysUtil;
this.releaseMessageService = releaseMessageService;
this.entityManagerUtil = entityManagerUtil;
Expand Down Expand Up @@ -111,15 +112,18 @@ public DeferredResult<ResponseEntity<List<ApolloConfigNotification>>> pollNotifi
DeferredResultWrapper deferredResultWrapper = new DeferredResultWrapper();
Set<String> namespaces = Sets.newHashSet();
Map<String, Long> clientSideNotifications = Maps.newHashMap();
Map<String, ApolloConfigNotification> filteredNotifications = filterNotifications(appId, notifications);
Map<String, ApolloConfigNotification> filteredNotifications = filterNotifications(appId,
notifications);

for (Map.Entry<String, ApolloConfigNotification> notificationEntry : filteredNotifications.entrySet()) {
for (Map.Entry<String, ApolloConfigNotification> notificationEntry : filteredNotifications
.entrySet()) {
String normalizedNamespace = notificationEntry.getKey();
ApolloConfigNotification notification = notificationEntry.getValue();
namespaces.add(normalizedNamespace);
clientSideNotifications.put(normalizedNamespace, notification.getNotificationId());
if (!Objects.equals(notification.getNamespaceName(), normalizedNamespace)) {
deferredResultWrapper.recordNamespaceNameNormalizedResult(notification.getNamespaceName(), normalizedNamespace);
deferredResultWrapper.recordNamespaceNameNormalizedResult(notification.getNamespaceName(),
normalizedNamespace);
}
}

Expand All @@ -131,25 +135,10 @@ public DeferredResult<ResponseEntity<List<ApolloConfigNotification>>> pollNotifi
watchKeysUtil.assembleAllWatchKeys(appId, cluster, namespaces, dataCenter);

Set<String> watchedKeys = Sets.newHashSet(watchedKeysMap.values());

List<ReleaseMessage> latestReleaseMessages =
releaseMessageService.findLatestReleaseMessagesGroupByMessages(watchedKeys);

/**
* Manually close the entity manager.
* Since for async request, Spring won't do so until the request is finished,
* which is unacceptable since we are doing long polling - means the db connection would be hold
* for a very long time
*/
entityManagerUtil.closeEntityManager();

List<ApolloConfigNotification> newNotifications =
getApolloConfigNotifications(namespaces, clientSideNotifications, watchedKeysMap,
latestReleaseMessages);

if (!CollectionUtils.isEmpty(newNotifications)) {
deferredResultWrapper.setResult(newNotifications);
} else {
//1、set deferredResult before check, for avoid more waiting
//If check before set deferredResult and release after check and release before set deferredResult,
//it will wait for more time.
{
Copy link
Member

@nobodyiam nobodyiam May 18, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code block is not necessary, it's also better to remove it.

deferredResultWrapper
.onTimeout(() -> logWatchedKeys(watchedKeys, "Apollo.LongPoll.TimeOutKeys"));

Expand All @@ -170,12 +159,30 @@ public DeferredResult<ResponseEntity<List<ApolloConfigNotification>>> pollNotifi
logger.debug("Listening {} from appId: {}, cluster: {}, namespace: {}, datacenter: {}",
watchedKeys, appId, cluster, namespaces, dataCenter);
}
//2、check new release
List<ReleaseMessage> latestReleaseMessages =
releaseMessageService.findLatestReleaseMessagesGroupByMessages(watchedKeys);

/**
* Manually close the entity manager.
* Since for async request, Spring won't do so until the request is finished,
* which is unacceptable since we are doing long polling - means the db connection would be hold
* for a very long time
*/
entityManagerUtil.closeEntityManager();

List<ApolloConfigNotification> newNotifications =
getApolloConfigNotifications(namespaces, clientSideNotifications, watchedKeysMap,
latestReleaseMessages);

if (!CollectionUtils.isEmpty(newNotifications)) {
deferredResultWrapper.setResult(newNotifications);
}
return deferredResultWrapper.getResult();
}

private Map<String, ApolloConfigNotification> filterNotifications(String appId,
List<ApolloConfigNotification> notifications) {
List<ApolloConfigNotification> notifications) {
Map<String, ApolloConfigNotification> filteredNotifications = Maps.newHashMap();
for (ApolloConfigNotification notification : notifications) {
if (Strings.isNullOrEmpty(notification.getNamespaceName())) {
Expand All @@ -191,7 +198,8 @@ private Map<String, ApolloConfigNotification> filterNotifications(String appId,
// such as FX.apollo = 1 but fx.apollo = 2, we should let FX.apollo have the chance to update its notification id
// which means we should record FX.apollo = 1 here and ignore fx.apollo = 2
if (filteredNotifications.containsKey(normalizedNamespace) &&
filteredNotifications.get(normalizedNamespace).getNotificationId() < notification.getNotificationId()) {
filteredNotifications.get(normalizedNamespace).getNotificationId() < notification
.getNotificationId()) {
continue;
}

Expand All @@ -201,9 +209,9 @@ private Map<String, ApolloConfigNotification> filterNotifications(String appId,
}

private List<ApolloConfigNotification> getApolloConfigNotifications(Set<String> namespaces,
Map<String, Long> clientSideNotifications,
Multimap<String, String> watchedKeysMap,
List<ReleaseMessage> latestReleaseMessages) {
Map<String, Long> clientSideNotifications,
Multimap<String, String> watchedKeysMap,
List<ReleaseMessage> latestReleaseMessages) {
List<ApolloConfigNotification> newNotifications = Lists.newArrayList();
if (!CollectionUtils.isEmpty(latestReleaseMessages)) {
Map<String, Long> latestNotifications = Maps.newHashMap();
Expand All @@ -217,15 +225,18 @@ private List<ApolloConfigNotification> getApolloConfigNotifications(Set<String>
Collection<String> namespaceWatchedKeys = watchedKeysMap.get(namespace);
for (String namespaceWatchedKey : namespaceWatchedKeys) {
long namespaceNotificationId =
latestNotifications.getOrDefault(namespaceWatchedKey, ConfigConsts.NOTIFICATION_ID_PLACEHOLDER);
latestNotifications
.getOrDefault(namespaceWatchedKey, ConfigConsts.NOTIFICATION_ID_PLACEHOLDER);
if (namespaceNotificationId > latestId) {
latestId = namespaceNotificationId;
}
}
if (latestId > clientSideId) {
ApolloConfigNotification notification = new ApolloConfigNotification(namespace, latestId);
namespaceWatchedKeys.stream().filter(latestNotifications::containsKey).forEach(namespaceWatchedKey ->
notification.addMessage(namespaceWatchedKey, latestNotifications.get(namespaceWatchedKey)));
namespaceWatchedKeys.stream().filter(latestNotifications::containsKey)
.forEach(namespaceWatchedKey ->
notification.addMessage(namespaceWatchedKey,
latestNotifications.get(namespaceWatchedKey)));
newNotifications.add(notification);
}
}
Expand Down Expand Up @@ -257,7 +268,8 @@ public void handleMessage(ReleaseMessage message, String channel) {
//create a new list to avoid ConcurrentModificationException
List<DeferredResultWrapper> results = Lists.newArrayList(deferredResults.get(content));

ApolloConfigNotification configNotification = new ApolloConfigNotification(changedNamespace, message.getId());
ApolloConfigNotification configNotification = new ApolloConfigNotification(changedNamespace,
message.getId());
configNotification.addMessage(content, message.getId());

//do async notification if too many clients
Expand All @@ -268,7 +280,8 @@ public void handleMessage(ReleaseMessage message, String channel) {
for (int i = 0; i < results.size(); i++) {
if (i > 0 && i % bizConfig.releaseMessageNotificationBatch() == 0) {
try {
TimeUnit.MILLISECONDS.sleep(bizConfig.releaseMessageNotificationBatchIntervalInMilli());
TimeUnit.MILLISECONDS
.sleep(bizConfig.releaseMessageNotificationBatchIntervalInMilli());
} catch (InterruptedException e) {
//ignore
}
Expand Down