Skip to content

Commit

Permalink
Refactor: Trigger the listener added for the first time (#225)
Browse files Browse the repository at this point in the history
* refactor: Trigger the listener added for the first time

* refactor: Trigger the watch listener before adding to watchers
  • Loading branch information
wallezhang authored Oct 14, 2022
1 parent 479f3f3 commit 11f1534
Showing 1 changed file with 15 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,18 @@
import com.tencent.polaris.client.util.NamedThreadFactory;
import com.tencent.polaris.client.util.Utils;
import com.tencent.polaris.logging.LoggerFactory;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import org.slf4j.Logger;

/**
Expand Down Expand Up @@ -77,7 +80,18 @@ public WatchServiceResponse commonWatchService(CommonWatchServiceRequest request
InstancesResponse response = syncFlow.commonSyncGetAllInstances(request.getAllRequest());
watchers.computeIfAbsent(request.getSvcEventKey().getServiceKey(),
key -> Collections.synchronizedSet(new HashSet<>()));
boolean result = watchers.get(serviceKey).addAll(request.getWatchServiceRequest().getListeners());
List<ServiceListener> addListeners = request.getWatchServiceRequest().getListeners();
Set<ServiceListener> existListeners = watchers.get(serviceKey);
List<ServiceListener> firstAddedListeners = addListeners.stream()
.filter(serviceListener -> !existListeners.contains(serviceListener)).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(firstAddedListeners)) {
ServiceChangeEvent event = ServiceChangeEvent.builder().serviceKey(serviceKey)
.addInstances(Arrays.asList(response.getInstances()))
.allInstances(Arrays.asList(response.getInstances())).build();
firstAddedListeners.forEach(
serviceListener -> executor.execute(event.getServiceKey(), () -> serviceListener.onEvent(event)));
}
boolean result = existListeners.addAll(addListeners);
return new WatchServiceResponse(response, result);
}

Expand Down

0 comments on commit 11f1534

Please sign in to comment.