Skip to content

Commit

Permalink
Add a CommandCenterProvider to resolve and cache the CommandCenter in…
Browse files Browse the repository at this point in the history
…stance (alibaba#409)
  • Loading branch information
cdfive authored and sczyh30 committed Mar 4, 2019
1 parent b54461b commit 61fede3
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 15 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.alibaba.csp.sentinel.command;

import com.alibaba.csp.sentinel.log.RecordLog;
import com.alibaba.csp.sentinel.transport.CommandCenter;
import com.alibaba.csp.sentinel.util.SpiLoader;

/**
* Provider for a universal {@link CommandCenter} instance.
*
* @author cdfive
* @date 2019-01-11
*/
public class CommandCenterProvider {

private static CommandCenter commandCenter = null;

static {
resolveInstance();
}

private static void resolveInstance() {
CommandCenter resolveCommandCenter = SpiLoader.loadFirstInstance(CommandCenter.class);

if (resolveCommandCenter == null) {
RecordLog.warn("[CommandCenterProvider] No existing CommandCenter, resolve failed");
} else {
commandCenter = resolveCommandCenter;
RecordLog.info("[CommandCenterProvider] CommandCenter resolved: " + resolveCommandCenter.getClass().getCanonicalName());
}
}

public static CommandCenter getCommandCenter() {
return commandCenter;
}

private CommandCenterProvider() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@
*/
package com.alibaba.csp.sentinel.transport.init;

import java.util.Iterator;
import java.util.ServiceLoader;

import com.alibaba.csp.sentinel.command.CommandCenterProvider;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.init.InitOrder;
import com.alibaba.csp.sentinel.log.RecordLog;
Expand All @@ -31,18 +29,16 @@ public class CommandCenterInitFunc implements InitFunc {

@Override
public void init() throws Exception {
ServiceLoader<CommandCenter> loader = ServiceLoader.load(CommandCenter.class);
Iterator<CommandCenter> iterator = loader.iterator();
if (iterator.hasNext()) {
CommandCenter commandCenter = iterator.next();
if (iterator.hasNext()) {
throw new IllegalStateException("Only single command center can be started");
} else {
commandCenter.beforeStart();
commandCenter.start();
RecordLog.info("[CommandCenterInit] Starting command center: "
+ commandCenter.getClass().getCanonicalName());
}
CommandCenter commandCenter = CommandCenterProvider.getCommandCenter();

if (commandCenter == null) {
RecordLog.warn("[CommandCenterInitFunc] Cannot resolve CommandCenter");
return;
}

commandCenter.beforeStart();
commandCenter.start();
RecordLog.info("[CommandCenterInit] Starting command center: "
+ commandCenter.getClass().getCanonicalName());
}
}

0 comments on commit 61fede3

Please sign in to comment.