Last active
May 7, 2016 06:53
-
-
Save nobodyiam/cfe3f3b1db782204f25b6408151cf841 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@RestController | |
@RequestMapping("/notifications") | |
public class NotificationControllerSample implements MessageListener { | |
private static final long TIMEOUT = 360 * 60 * 1000;//6 hours | |
private final Multimap<String, DeferredResult<ResponseEntity<ApolloConfigNotification>>> | |
deferredResults = Multimaps.synchronizedSetMultimap(HashMultimap.create()); | |
private static final ResponseEntity<ApolloConfigNotification> | |
NOT_MODIFIED_RESPONSE = new ResponseEntity<>(HttpStatus.NOT_MODIFIED); | |
@RequestMapping(method = RequestMethod.GET) | |
public DeferredResult<ResponseEntity<ApolloConfigNotification>> pollNotification( | |
@RequestParam(value = "appId") String appId, | |
@RequestParam(value = "cluster") String cluster, | |
@RequestParam(value = "namespace", defaultValue = ConfigConsts.NAMESPACE_DEFAULT) String namespace, | |
@RequestParam(value = "dataCenter", required = false) { | |
//calcuate watched keys, will load from db in some cases | |
List<String> watchedKeys = findWatchedKeys(appId, namespace, dataCenter); | |
DeferredResult<ResponseEntity<ApolloConfigNotification>> deferredResult = | |
new DeferredResult<>(TIMEOUT, NOT_MODIFIED_RESPONSE); | |
//register all keys | |
for (String key : watchedKeys) { | |
this.deferredResults.put(key, deferredResult); | |
} | |
deferredResult.onCompletion(() -> { | |
//unregister all keys | |
for (String key : watchedKeys) { | |
deferredResults.remove(key, deferredResult); | |
} | |
}); | |
return deferredResult; | |
} | |
private List<String> findWatchedKeys(String applicationId, String namespace, | |
String dataCenter) { | |
List<String> watchedKeys = Lists.newArrayList(); | |
//do more logic, may need to load from db in some cases | |
return watchedKeys; | |
} | |
@Override | |
public void handleMessage(String key, String channel) { | |
ResponseEntity<ApolloConfigNotification> notification = | |
new ResponseEntity<>(new ApolloConfigNotification(key, HttpStatus.OK); | |
//create a new list to avoid ConcurrentModificationException | |
List<DeferredResult<ResponseEntity<ApolloConfigNotification>>> results = | |
Lists.newArrayList(deferredResults.get(key)); | |
for (DeferredResult<ResponseEntity<ApolloConfigNotification>> result : results) { | |
result.setResult(notification); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment