|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | +package com.alipay.sofa.rpc.hystrix; |
| 18 | + |
| 19 | +import com.alipay.sofa.rpc.common.utils.ClassUtils; |
| 20 | +import com.alipay.sofa.rpc.config.ConsumerConfig; |
| 21 | +import com.alipay.sofa.rpc.context.RpcInternalContext; |
| 22 | +import com.alipay.sofa.rpc.context.RpcInvokeContext; |
| 23 | +import com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException; |
| 24 | +import com.alipay.sofa.rpc.core.exception.SofaTimeOutException; |
| 25 | +import com.alipay.sofa.rpc.core.request.SofaRequest; |
| 26 | +import com.alipay.sofa.rpc.core.response.SofaResponse; |
| 27 | +import com.alipay.sofa.rpc.filter.FilterInvoker; |
| 28 | +import com.alipay.sofa.rpc.log.Logger; |
| 29 | +import com.alipay.sofa.rpc.log.LoggerFactory; |
| 30 | +import com.alipay.sofa.rpc.message.ResponseFuture; |
| 31 | +import com.netflix.hystrix.HystrixCommand; |
| 32 | +import com.netflix.hystrix.HystrixEventType; |
| 33 | + |
| 34 | +import java.lang.reflect.InvocationTargetException; |
| 35 | +import java.lang.reflect.Method; |
| 36 | +import java.util.ArrayList; |
| 37 | +import java.util.Collections; |
| 38 | +import java.util.List; |
| 39 | +import java.util.concurrent.CountDownLatch; |
| 40 | +import java.util.concurrent.TimeUnit; |
| 41 | + |
| 42 | +/** |
| 43 | + * {@link HystrixCommand} for async requests |
| 44 | + * |
| 45 | + * @author <a href=mailto:[email protected]>ScienJus</a> |
| 46 | + */ |
| 47 | +public class SofaAsyncHystrixCommand extends HystrixCommand implements SofaHystrixInvokable { |
| 48 | + |
| 49 | + private static final Logger LOGGER = LoggerFactory |
| 50 | + .getLogger(SofaAsyncHystrixCommand.class); |
| 51 | + |
| 52 | + private static final long DEFAULT_LOCK_TIMEOUT = 1000; |
| 53 | + |
| 54 | + private final FilterInvoker invoker; |
| 55 | + |
| 56 | + private final SofaRequest request; |
| 57 | + |
| 58 | + private final RpcInternalContext rpcInternalContext; |
| 59 | + |
| 60 | + private final RpcInvokeContext rpcInvokeContext; |
| 61 | + |
| 62 | + private final CountDownLatch lock = new CountDownLatch(1); |
| 63 | + |
| 64 | + private final List<SofaAsyncHystrixEvent> events = new ArrayList<SofaAsyncHystrixEvent>(); |
| 65 | + |
| 66 | + private SofaResponse sofaResponse; |
| 67 | + |
| 68 | + public SofaAsyncHystrixCommand(FilterInvoker invoker, SofaRequest request) { |
| 69 | + super(SofaHystrixConfig.loadSetterFactory((ConsumerConfig) invoker.getConfig()).createSetter(invoker, |
| 70 | + request)); |
| 71 | + this.rpcInternalContext = RpcInternalContext.peekContext(); |
| 72 | + this.rpcInvokeContext = RpcInvokeContext.peekContext(); |
| 73 | + this.invoker = invoker; |
| 74 | + this.request = request; |
| 75 | + } |
| 76 | + |
| 77 | + @Override |
| 78 | + public SofaResponse invoke() { |
| 79 | + if (isCircuitBreakerOpen() && LOGGER.isWarnEnabled(invoker.getConfig().getAppName())) { |
| 80 | + LOGGER.warnWithApp(invoker.getConfig().getAppName(), "Circuit Breaker is opened, method: {}#{}", |
| 81 | + invoker.getConfig().getInterfaceId(), request.getMethodName()); |
| 82 | + } |
| 83 | + HystrixResponseFuture delegate = new HystrixResponseFuture(this.queue()); |
| 84 | + try { |
| 85 | + boolean finished = lock.await(getLockTimeout(), TimeUnit.MILLISECONDS); |
| 86 | + if (!finished && !this.isExecutionComplete()) { |
| 87 | + throw new SofaTimeOutException( |
| 88 | + "Asynchronous execution timed out, please check Hystrix configuration. Events: " + |
| 89 | + getExecutionEventsString()); |
| 90 | + } |
| 91 | + } catch (InterruptedException e) { |
| 92 | + Thread.currentThread().interrupt(); |
| 93 | + } |
| 94 | + RpcInternalContext.getContext().setFuture(delegate); |
| 95 | + if (this.sofaResponse == null) { |
| 96 | + this.sofaResponse = buildEmptyResponse(request); |
| 97 | + } |
| 98 | + return this.sofaResponse; |
| 99 | + } |
| 100 | + |
| 101 | + @Override |
| 102 | + protected Object run() throws Exception { |
| 103 | + events.add(SofaAsyncHystrixEvent.EMIT); |
| 104 | + RpcInternalContext.setContext(rpcInternalContext); |
| 105 | + RpcInvokeContext.setContext(rpcInvokeContext); |
| 106 | + |
| 107 | + this.sofaResponse = invoker.invoke(request); |
| 108 | + ResponseFuture responseFuture = RpcInternalContext.getContext().getFuture(); |
| 109 | + lock.countDown(); |
| 110 | + events.add(SofaAsyncHystrixEvent.INVOKE_UNLOCKED); |
| 111 | + try { |
| 112 | + return responseFuture.get(); |
| 113 | + } finally { |
| 114 | + events.add(SofaAsyncHystrixEvent.INVOKE_SUCCESS); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + @Override |
| 119 | + protected Object getFallback() { |
| 120 | + events.add(SofaAsyncHystrixEvent.FALLBACK_EMIT); |
| 121 | + if (lock.getCount() > 0) { |
| 122 | + // > 0 说明 run 方法没有执行,或是执行时立刻失败了 |
| 123 | + this.sofaResponse = buildEmptyResponse(request); |
| 124 | + lock.countDown(); |
| 125 | + events.add(SofaAsyncHystrixEvent.FALLBACK_UNLOCKED); |
| 126 | + } |
| 127 | + FallbackFactory fallbackFactory = SofaHystrixConfig.loadFallbackFactory((ConsumerConfig) invoker.getConfig()); |
| 128 | + if (fallbackFactory == null) { |
| 129 | + return super.getFallback(); |
| 130 | + } |
| 131 | + Object fallback = fallbackFactory.create(null, this.getExecutionException()); |
| 132 | + if (fallback == null) { |
| 133 | + return super.getFallback(); |
| 134 | + } |
| 135 | + try { |
| 136 | + return request.getMethod().invoke(fallback, request.getMethodArgs()); |
| 137 | + } catch (IllegalAccessException e) { |
| 138 | + throw new SofaRpcRuntimeException("Hystrix fallback method failed to execute.", e); |
| 139 | + } catch (InvocationTargetException e) { |
| 140 | + throw new SofaRpcRuntimeException("Hystrix fallback method failed to execute.", |
| 141 | + e.getTargetException()); |
| 142 | + } finally { |
| 143 | + events.add(SofaAsyncHystrixEvent.FALLBACK_SUCCESS); |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + // Copy from AbstractCluster#buildEmptyResponse |
| 148 | + private SofaResponse buildEmptyResponse(SofaRequest request) { |
| 149 | + SofaResponse response = new SofaResponse(); |
| 150 | + Method method = request.getMethod(); |
| 151 | + if (method != null) { |
| 152 | + response.setAppResponse(ClassUtils.getDefaultPrimitiveValue(method.getReturnType())); |
| 153 | + } |
| 154 | + return response; |
| 155 | + } |
| 156 | + |
| 157 | + private long getLockTimeout() { |
| 158 | + if (this.getProperties().executionTimeoutEnabled().get()) { |
| 159 | + return this.getProperties().executionTimeoutInMilliseconds().get(); |
| 160 | + } |
| 161 | + return DEFAULT_LOCK_TIMEOUT; |
| 162 | + } |
| 163 | + |
| 164 | + private String getExecutionEventsString() { |
| 165 | + List<HystrixEventType> executionEvents = getExecutionEvents(); |
| 166 | + if (executionEvents == null) { |
| 167 | + executionEvents = Collections.emptyList(); |
| 168 | + } |
| 169 | + StringBuilder message = new StringBuilder("["); |
| 170 | + for (HystrixEventType executionEvent : executionEvents) { |
| 171 | + message.append(HystrixEventType.class.getSimpleName()).append("#").append(executionEvent.name()) |
| 172 | + .append(","); |
| 173 | + } |
| 174 | + for (SofaAsyncHystrixEvent event : events) { |
| 175 | + message.append(SofaAsyncHystrixEvent.class.getSimpleName()).append("#").append(event.name()).append(","); |
| 176 | + } |
| 177 | + if (message.length() > 1) { |
| 178 | + message.deleteCharAt(message.length() - 1); |
| 179 | + } |
| 180 | + return message.append("]").toString(); |
| 181 | + } |
| 182 | +} |
0 commit comments