本文主要研究一下dubbo-go的gracefulShutdownFilter
dubbo-go-v1.4.2/filter/filter_impl/graceful_shutdown_filter.go
type gracefulShutdownFilter struct { activeCount int32 shutdownConfig *config.ShutdownConfig }
dubbo-go-v1.4.2/filter/filter_impl/graceful_shutdown_filter.go
func init() { var consumerFiler = &gracefulShutdownFilter{ shutdownConfig: config.GetConsumerConfig().ShutdownConfig, } var providerFilter = &gracefulShutdownFilter{ shutdownConfig: config.GetProviderConfig().ShutdownConfig, } extension.SetFilter(constant.CONSUMER_SHUTDOWN_FILTER, func() filter.Filter { return consumerFiler }) extension.SetFilter(constant.PROVIDER_SHUTDOWN_FILTER, func() filter.Filter { return providerFilter }) }
dubbo-go-v1.4.2/filter/filter_impl/graceful_shutdown_filter.go
func (gf *gracefulShutdownFilter) Invoke(ctx context.Context, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result { if gf.rejectNewRequest() { logger.Info("The application is closing, new request will be rejected.") return gf.getRejectHandler().RejectedExecution(invoker.GetUrl(), invocation) } atomic.AddInt32(&gf.activeCount, 1) return invoker.Invoke(ctx, invocation) }
dubbo-go-v1.4.2/filter/filter_impl/graceful_shutdown_filter.go
func (gf *gracefulShutdownFilter) OnResponse(ctx context.Context, result protocol.Result, invoker protocol.Invoker, invocation protocol.Invocation) protocol.Result { atomic.AddInt32(&gf.activeCount, -1) // although this isn't thread safe, it won't be a problem if the gf.rejectNewRequest() is true. if gf.shutdownConfig != nil && gf.activeCount <= 0 { gf.shutdownConfig.RequestsFinished = true } return result }
dubbo-go-v1.4.2/filter/filter_impl/graceful_shutdown_filter.go
func (gf *gracefulShutdownFilter) rejectNewRequest() bool { if gf.shutdownConfig == nil { return false } return gf.shutdownConfig.RejectRequest }
dubbo-go-v1.4.2/filter/filter_impl/graceful_shutdown_filter.go
func (gf *gracefulShutdownFilter) getRejectHandler() filter.RejectedExecutionHandler { handler := constant.DEFAULT_KEY if gf.shutdownConfig != nil && len(gf.shutdownConfig.RejectRequestHandler) > 0 { handler = gf.shutdownConfig.RejectRequestHandler } return extension.GetRejectedExecutionHandler(handler) }
gracefulShutdownFilter定义了activeCount、shutdownConfig属性;其Invoke方法先判断gracefulShutdownFilter的rejectNewRequest是否为true,若为true则执行getRejectHandler().RejectedExecution,否则执行atomic.AddInt32及invoker.Invoke(ctx, invocation);其OnResponse方法先执行atomic.AddInt32(&gf.activeCount, -1),之后判断gf.activeCount是否小于等于0,是的话则标记gf.shutdownConfig.RequestsFinished为true