乐趣区

关于dubbo:聊聊dubbogo的failsafeCluster

本文次要钻研一下 dubbo-go 的 failsafeCluster

failsafeCluster

dubbo-go-v1.4.2/cluster/cluster_impl/failsafe_cluster.go

type failsafeCluster struct{}

const failsafe = "failsafe"

func init() {extension.SetCluster(failsafe, NewFailsafeCluster)
}

// NewFailsafeCluster ...
func NewFailsafeCluster() cluster.Cluster {return &failsafeCluster{}
}

func (cluster *failsafeCluster) Join(directory cluster.Directory) protocol.Invoker {return newFailsafeClusterInvoker(directory)
}
  • failsafeCluster 的 join 办法执行 newFailsafeClusterInvoker

newFailsafeClusterInvoker

dubbo-go-v1.4.2/cluster/cluster_impl/failsafe_cluster_invoker.go

type failsafeClusterInvoker struct {baseClusterInvoker}

func newFailsafeClusterInvoker(directory cluster.Directory) protocol.Invoker {
    return &failsafeClusterInvoker{baseClusterInvoker: newBaseClusterInvoker(directory),
    }
}
  • newFailsafeClusterInvoker 办法创立 failsafeClusterInvoker

Invoke

dubbo-go-v1.4.2/cluster/cluster_impl/failsafe_cluster_invoker.go

func (invoker *failsafeClusterInvoker) Invoke(ctx context.Context, invocation protocol.Invocation) protocol.Result {invokers := invoker.directory.List(invocation)

    err := invoker.checkInvokers(invokers, invocation)
    if err != nil {return &protocol.RPCResult{}
    }

    url := invokers[0].GetUrl()
    methodName := invocation.MethodName()
    //Get the service loadbalance config
    lb := url.GetParam(constant.LOADBALANCE_KEY, constant.DEFAULT_LOADBALANCE)
    //Get the service method loadbalance config if have
    if v := url.GetMethodParam(methodName, constant.LOADBALANCE_KEY, ""); v !="" {lb = v}
    loadbalance := extension.GetLoadbalance(lb)

    invoked := make([]protocol.Invoker, 0)
    var result protocol.Result

    ivk := invoker.doSelect(loadbalance, invocation, invokers, invoked)
    //DO INVOKE
    result = ivk.Invoke(ctx, invocation)
    if result.Error() != nil {
        // ignore
        logger.Errorf("Failsafe ignore exception: %v.\n", result.Error().Error())
        return &protocol.RPCResult{}}
    return result
}
  • Invoke 办法先通过 invoker.directory.List(invocation) 获取 invokers,之后通过 invoker.doSelect(loadbalance, invocation, invokers, invoked) 抉择 ivk,最初执行 ivk.Invoke(ctx, invocation),如果有 error,则打印 error,返回空后果

GetLoadbalance

dubbo-go-v1.4.2/common/extension/loadbalance.go

// GetLoadbalance ...
func GetLoadbalance(name string) cluster.LoadBalance {if loadbalances[name] == nil {panic("loadbalance for" + name + "is not existing, make sure you have import the package.")
    }

    return loadbalances[name]()}
  • GetLoadbalance 办法依据执行的 name 获取 cluster.LoadBalance,默认为 randomLoadBalance

小结

failsafeCluster 的 join 办法执行 newFailsafeClusterInvoker;Invoke 办法先通过 invoker.directory.List(invocation) 获取 invokers,之后通过 invoker.doSelect(loadbalance, invocation, invokers, invoked) 抉择 ivk,最初执行 ivk.Invoke(ctx, invocation),如果有 error,则打印 error,返回空后果

与 failfastCluster 的区别就是针对 error 进行 log,而后返回的始终的是没有 err 的

退出移动版