篇首语:本文由编程笔记#小编为大家整理,主要介绍了Dubbo集群简介相关的知识,希望对你有一定的参考价值。
目录
为避免单点故障,通常会部署多台服务器。作为服务消费者,在调用时需要考虑:
ClusterInvoker
选择服务提供者的大概过程如下:
Directory#list()
获取Invoker列表(该列表经过路由过滤):LoadBalance#select()
获取最终的InvokerDubbo定义了两个集群对象:
示例代码如下:
public class FailoverCluster implements Cluster {
public final static String NAME = "failover";
@Override
public
return new FailoverClusterInvoker
}
}
该方法会执行如下逻辑:
@Override
public Result invoke(final Invocation invocation) throws RpcException {
checkWhetherDestroyed();
LoadBalance loadbalance = null;
// 绑定attachments到invocation中.
Map
if (contextAttachments != null && contextAttachments.size() != 0) {
((RpcInvocation) invocation).addAttachments(contextAttachments);
}
// 从服务目录中获取Invoker列表
List
if (invokers != null && !invokers.isEmpty()) {
loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(invokers.get(0).getUrl()
.getMethodParameter(RpcUtils.getMethodName(invocation), Constants.LOADBALANCE_KEY, Constants.DEFAULT_LOADBALANCE));
}
RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
// 执行Invoker
return doInvoke(invocation, invokers, loadbalance);
}
该方法用于从服务目录中获取Invoker列表,代码十分简单,如下:
protected List
List
return invokers;
}
select()
方法主要逻辑:
// invokers:服务目录中获取的所有Invoker列表
// invoked:在本次调用中,已经执行过的invokers列表
protected Invoker
if (invokers == null || invokers.isEmpty())
return null;
// 获取调用方法
String methodName = invocation == null ? "" : invocation.getMethodName();
// 获取sticky属性(粘带属性)
boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY);
{
// 如果stickyInvoker!=null且invokers列表也不包含stickyInvoker,说明stickyInvoker代表的服务提供者挂了
if (stickyInvoker != null && !invokers.contains(stickyInvoker)) {
stickyInvoker = null;
}
//如果sticky==true且stickyInvoker!=null,此时如果selected包含stickyInvoker
//说明stickyInvoker对应服务提供者可能因为网络问题未能成功提供服务,但该提供者并没有挂(invokers仍包含stickyInvoker)
if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) {
// availablecheck是否开启可用性检查,若开启,检测stickyInvoker是否可用
if (availablecheck && stickyInvoker.isAvailable()) {
return stickyInvoker;
}
}
}
// 若代码走到此处,说明stickyInvoker==null,或不可用
Invoker
if (sticky) {
stickyInvoker = invoker;
}
return invoker;
}
doSelect
方法用于真正去筛选Invoker:
private Invoker
if (invokers == null || invokers.isEmpty())
return null;
if (invokers.size() == 1)
return invokers.get(0);
if (loadbalance == null) {
loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(Constants.DEFAULT_LOADBALANCE);
}
Invoker
//如果selected包含负载均衡选择出的Invoker,或者该Invoker无法经过可用性检查,此时进行重选
if ((selected != null && selected.contains(invoker))
|| (!invoker.isAvailable() && getUrl() != null && availablecheck)) {
try {
Invoker
if (rinvoker != null) {
invoker = rinvoker;
} else {
//Check the index of current selected invoker, if it's not the last one, choose the one at index+1.
int index = invokers.indexOf(invoker);
try {
//Avoid collision
invoker = index
}
} catch (Throwable t) { /* 日志 */ }
}
return invoker;
}
十分简单:失败则循环调用。循环次数可配置,默认3次。
public class FailoverClusterInvoker
private static final Logger logger = LoggerFactory.getLogger(FailoverClusterInvoker.class);
public FailoverClusterInvoker(Directory
super(directory);
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public Result doInvoke(Invocation invocation, final List
List
checkInvokers(copyinvokers, invocation);
int len = getUrl().getMethodParameter(invocation.getMethodName(), Constants.RETRIES_KEY, Constants.DEFAULT_RETRIES) + 1;
if (len <= 0) {
len = 1;
}
// retry loop.
RpcException le = null; // last exception.
List
Set
for (int i = 0; i
//NOTE: if `invokers` changed, then `invoked` also lose accuracy.
if (i > 0) {
checkWhetherDestroyed();
copyinvokers = list(invocation);
// check again
checkInvokers(copyinvokers, invocation);
}
Invoker
invoked.add(invoker);
RpcContext.getContext().setInvokers((List) invoked);
try {
Result result = invoker.invoke(invocation);
if (le != null && logger.isWarnEnabled()) {
//
}
return result;
} catch (RpcException e) {
if (e.isBiz()) { // biz exception.
throw e;
}
le = e;
} catch (Throwable e) {
le = new RpcException(e.getMessage(), e);
} finally {
providers.add(invoker.getUrl().getAddress());
}
}
throw new RpcException(...);
}
}
调用失败,返回空结果给服务提供者,定时任务对失败的调用进行补偿,适合执行消息通知等操作,如下:
public class FailbackClusterInvoker
private static final Logger logger = LoggerFactory.getLogger(FailbackClusterInvoker.class);
private static final long RETRY_FAILED_PERIOD = 5 * 1000;
private final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2,
new NamedInternalThreadFactory("failback-cluster-timer", true));
private final ConcurrentMap
private volatile ScheduledFuture> retryFuture;
public FailbackClusterInvoker(Directory
super(directory);
}
// 放入失败队列Map结构中
private void addFailed(Invocation invocation, AbstractClusterInvoker> router) {
if (retryFuture == null) {
synchronized (this) {
if (retryFuture == null) {
retryFuture = scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
// collect retry statistics
try {
retryFailed();
} catch (Throwable t) { // Defensive fault tolerance
logger.error("Unexpected error occur at collect statistic", t);
}
}
}, RETRY_FAILED_PERIOD, RETRY_FAILED_PERIOD, TimeUnit.MILLISECONDS);
}
}
}
failed.put(invocation, router);
}
// 失败重试
void retryFailed() {
if (failed.size() == 0) {
return;
}
for (Map.Entry
failed).entrySet()) {
Invocation invocation = entry.getKey();
Invoker> invoker = entry.getValue();
try {
invoker.invoke(invocation);
failed.remove(invocation);
} catch (Throwable e) {
logger.error("Failed retry to invoke method " + invocation.getMethodName() + ", waiting again.", e);
}
}
}
@Override
protected Result doInvoke(Invocation invocation, List
try {
checkInvokers(invokers, invocation);
Invoker
return invoker.invoke(invocation);
} catch (Throwable e) {
/* 日志 */
addFailed(invocation, this);
return new RpcResult(); // ignore
}
}
}
调用一次,快速失败,失败后立即抛出异常:
public class FailfastClusterInvoker
public FailfastClusterInvoker(Directory
super(directory);
}
@Override
public Result doInvoke(Invocation invocation, List
checkInvokers(invokers, invocation);
Invoker
try {
return invoker.invoke(invocation);
} catch (Throwable e) {
if (e instanceof RpcException && ((RpcException) e).isBiz()) { // biz exception.
throw (RpcException) e;
}
throw new RpcException(e instanceof RpcException ? ((RpcException) e).getCode() : 0, "Failfast invoke providers " + invoker.getUrl() + " " + loadbalance.getClass().getSimpleName() + " select from all providers " + invokers + " for service " + getInterface().getName() + " method " + invocation.getMethodName() + " on consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", but no luck to perform the invocation. Last error is: " + e.getMessage(), e.getCause() != null ? e.getCause() : e);
}
}
}
调用一次,快速失败,失败仅打印日志,不抛出异常
public class FailsafeClusterInvoker
private static final Logger logger = LoggerFactory.getLogger(FailsafeClusterInvoker.class);
public FailsafeClusterInvoker(Directory
super(directory);
}
@Override
public Result doInvoke(Invocation invocation, List
try {
checkInvokers(invokers, invocation);
Invoker
return invoker.invoke(invocation);
} catch (Throwable e) {
logger.error("Failsafe ignore exception: " + e.getMessage(), e);
return new RpcResult(); // ignore
}
}
}