Repository: camel Updated Branches: refs/heads/master a4a630e06 -> 4261f1121
Added a new component based on Hystrix library Project: http://git-wip-us.apache.org/repos/asf/camel/repo Commit: http://git-wip-us.apache.org/repos/asf/camel/commit/4261f112 Tree: http://git-wip-us.apache.org/repos/asf/camel/tree/4261f112 Diff: http://git-wip-us.apache.org/repos/asf/camel/diff/4261f112 Branch: refs/heads/master Commit: 4261f112127d184e5205626860023b8dc1201eea Parents: a4a630e Author: bibryam <bibr...@apache.org> Authored: Fri Mar 25 13:28:59 2016 +0000 Committer: bibryam <bibr...@apache.org> Committed: Fri Mar 25 13:28:59 2016 +0000 ---------------------------------------------------------------------- apache-camel/pom.xml | 4 + components/camel-hystrix/pom.xml | 60 +++ .../component/hystrix/CamelHystrixCommand.java | 78 ++++ .../component/hystrix/HystrixComponent.java | 38 ++ .../component/hystrix/HystrixConfiguration.java | 383 +++++++++++++++++++ .../component/hystrix/HystrixConstants.java | 22 ++ .../component/hystrix/HystrixEndpoint.java | 88 +++++ .../component/hystrix/HystrixProducer.java | 233 +++++++++++ .../src/main/resources/META-INF/LICENSE.txt | 203 ++++++++++ .../src/main/resources/META-INF/NOTICE.txt | 11 + .../services/org/apache/camel/component/hystrix | 18 + .../HystrixComponentCircuitBreakerTest.java | 100 +++++ .../HystrixComponentRequestContextTest.java | 120 ++++++ .../component/hystrix/HystrixComponentTest.java | 154 ++++++++ .../src/test/resources/log4j.properties | 36 ++ components/pom.xml | 1 + parent/pom.xml | 7 + .../src/main/resources/bundles.properties | 1 + .../features/src/main/resources/features.xml | 5 + 19 files changed, 1562 insertions(+) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/apache-camel/pom.xml ---------------------------------------------------------------------- diff --git a/apache-camel/pom.xml b/apache-camel/pom.xml index b92593e..faf142e 100644 --- a/apache-camel/pom.xml +++ b/apache-camel/pom.xml @@ -353,6 +353,10 @@ </dependency> <dependency> <groupId>org.apache.camel</groupId> + <artifactId>camel-hystrix</artifactId> + </dependency> + <dependency> + <groupId>org.apache.camel</groupId> <artifactId>camel-ibatis</artifactId> </dependency> <dependency> http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/components/camel-hystrix/pom.xml ---------------------------------------------------------------------- diff --git a/components/camel-hystrix/pom.xml b/components/camel-hystrix/pom.xml new file mode 100644 index 0000000..47cc9f2 --- /dev/null +++ b/components/camel-hystrix/pom.xml @@ -0,0 +1,60 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.apache.camel</groupId> + <artifactId>components</artifactId> + <version>2.18-SNAPSHOT</version> + </parent> + + <artifactId>camel-hystrix</artifactId> + <packaging>bundle</packaging> + <name>Camel :: Hystrix</name> + <description>Camel Hystrix support</description> + + <properties> + <camel.osgi.export.pkg>org.apache.camel.component.hystrix.*</camel.osgi.export.pkg> + <camel.osgi.export.service>org.apache.camel.spi.ComponentResolver;component=hystrix</camel.osgi.export.service> + </properties> + + <dependencies> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-core</artifactId> + </dependency> + <dependency> + <groupId>com.netflix.hystrix</groupId> + <artifactId>hystrix-core</artifactId> + <version>${hystrix-version}</version> + </dependency> + + <!-- for testing --> + <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-test</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-log4j12</artifactId> + <scope>test</scope> + </dependency> + </dependencies> +</project> http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/CamelHystrixCommand.java ---------------------------------------------------------------------- diff --git a/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/CamelHystrixCommand.java b/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/CamelHystrixCommand.java new file mode 100644 index 0000000..b728d37 --- /dev/null +++ b/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/CamelHystrixCommand.java @@ -0,0 +1,78 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.hystrix; + +import com.netflix.hystrix.HystrixCommand; +import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; +import org.apache.camel.util.CamelContextHelper; + +public class CamelHystrixCommand extends HystrixCommand<Exchange> { + private final Exchange exchange; + private final String cacheKey; + private String runEndpointId; + private String fallbackEndpointId; + + protected CamelHystrixCommand(Setter setter, Exchange exchange, String cacheKey, String runEndpointId, String fallbackEndpointId) { + super(setter); + this.exchange = exchange; + this.cacheKey = cacheKey; + this.runEndpointId = runEndpointId; + this.fallbackEndpointId = fallbackEndpointId; + } + + @Override + protected String getCacheKey() { + return cacheKey; + } + + @Override + protected Exchange getFallback() { + if (fallbackEndpointId == null) { + super.getFallback(); + } + try { + Endpoint endpoint = findEndpoint(fallbackEndpointId); + endpoint.createProducer().process(exchange); + } catch (Exception e) { + throw new RuntimeException(e.getMessage()); + } + return exchange; + } + + @Override + protected Exchange run() { + try { + Endpoint endpoint = findEndpoint(runEndpointId); + endpoint.createProducer().process(exchange); + } catch (Exception e) { + exchange.setException(null); + throw new RuntimeException(e.getMessage()); + } + + if (exchange.getException() != null) { + Exception exception = exchange.getException(); + exchange.setException(null); + throw new RuntimeException(exception.getMessage()); + } + return exchange; + } + + private Endpoint findEndpoint(String endpointId) { + return CamelContextHelper.mandatoryLookup(exchange.getContext(), endpointId, Endpoint.class); + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixComponent.java ---------------------------------------------------------------------- diff --git a/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixComponent.java b/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixComponent.java new file mode 100644 index 0000000..2fe995e --- /dev/null +++ b/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixComponent.java @@ -0,0 +1,38 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.hystrix; + +import java.util.Map; +import org.apache.camel.Endpoint; +import org.apache.camel.impl.UriEndpointComponent; + +/** + * Represents the component that manages {@link HystrixComponent}. + */ +public class HystrixComponent extends UriEndpointComponent { + + public HystrixComponent() { + super(HystrixEndpoint.class); + } + + protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { + HystrixConfiguration configuration = new HystrixConfiguration(); + configuration.setGroupKey(remaining); + setProperties(configuration, parameters); + return new HystrixEndpoint(uri, this, configuration); + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixConfiguration.java ---------------------------------------------------------------------- diff --git a/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixConfiguration.java b/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixConfiguration.java new file mode 100644 index 0000000..8e0ee8e --- /dev/null +++ b/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixConfiguration.java @@ -0,0 +1,383 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.hystrix; + +import org.apache.camel.Expression; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.UriParam; +import org.apache.camel.spi.UriParams; +import org.apache.camel.spi.UriPath; + +@UriParams +public class HystrixConfiguration { + + /** + * Specifies the groupKey to use + */ + @UriPath + @Metadata(required = "true") + private String groupKey; + + /** + * Specifies the commandKey to use + */ + @UriParam(label = "producer") + private String commandKey; + + /** + * Specifies the threadPoolKey to use + */ + @UriParam(label = "producer") + private String threadPoolKey; + + /** + * Specifies the cacheKeyExpression to use + */ + @UriParam(label = "producer") + private Expression cacheKeyExpression; + + + /** + * Specifies the propagateRequestContext to use + */ + @UriParam(label = "producer") + private Boolean propagateRequestContext; + + /** + * Specifies the endpoint to use + */ + @UriParam(label = "producer") + private String runEndpointId; + + /** + * Specifies the fallbackEndpointId to use + */ + @UriParam(label = "producer") + private String fallbackEndpointId; + + private Integer coreSize; + private Integer keepAliveTimeMinutes; + private Integer maxQueueSize; + private Integer queueSizeRejectionThreshold; + private Integer rollingStatisticalWindowInMilliseconds; + private Integer rollingStatisticalWindowBuckets; + + private Boolean circuitBreakerEnabled; + private Integer circuitBreakerErrorThresholdPercentage; + private Boolean circuitBreakerForceClosed; + private Boolean circuitBreakerForceOpen; + private Integer circuitBreakerRequestVolumeThreshold; + private Integer circuitBreakerSleepWindowInMilliseconds; + private Integer executionIsolationSemaphoreMaxConcurrentRequests; + private String executionIsolationStrategy; + private Boolean executionIsolationThreadInterruptOnTimeout; + private Integer executionTimeoutInMilliseconds; + private Boolean executionTimeoutEnabled; + private Integer fallbackIsolationSemaphoreMaxConcurrentRequests; + private Boolean fallbackEnabled; + private Integer metricsHealthSnapshotIntervalInMilliseconds; + private Integer metricsRollingPercentileBucketSize; + private Boolean metricsRollingPercentileEnabled; + private Integer metricsRollingPercentileWindowInMilliseconds; + private Integer metricsRollingPercentileWindowBuckets; + /* null means it hasn't been overridden */ + private Integer metricsRollingStatisticalWindowInMilliseconds; + private Integer metricsRollingStatisticalWindowBuckets; + private Boolean requestCacheEnabled; + private Boolean requestLogEnabled; + + public String getRunEndpointId() { + return runEndpointId; + } + + public void setRunEndpointId(String runEndpointId) { + this.runEndpointId = runEndpointId; + } + + public String getFallbackEndpointId() { + return fallbackEndpointId; + } + + public void setFallbackEndpointId(String fallbackEndpointId) { + this.fallbackEndpointId = fallbackEndpointId; + } + + public Expression getCacheKeyExpression() { + return cacheKeyExpression; + } + + public void setCacheKeyExpression(Expression cacheKeyExpression) { + this.cacheKeyExpression = cacheKeyExpression; + } + + + public Boolean getPropagateRequestContext() { + return propagateRequestContext; + } + + public void setPropagateRequestContext(Boolean propagateRequestContext) { + this.propagateRequestContext = propagateRequestContext; + } + + public String getGroupKey() { + return groupKey; + } + + public void setGroupKey(String groupKey) { + this.groupKey = groupKey; + } + + public String getCommandKey() { + return commandKey; + } + + public void setCommandKey(String commandKey) { + this.commandKey = commandKey; + } + + public String getThreadPoolKey() { + return threadPoolKey; + } + + public void setThreadPoolKey(String threadPoolKey) { + this.threadPoolKey = threadPoolKey; + } + + public Integer getCoreSize() { + return coreSize; + } + + public void setCoreSize(Integer coreSize) { + this.coreSize = coreSize; + } + + public Integer getKeepAliveTimeMinutes() { + return keepAliveTimeMinutes; + } + + public void setKeepAliveTimeMinutes(Integer keepAliveTimeMinutes) { + this.keepAliveTimeMinutes = keepAliveTimeMinutes; + } + + public Integer getMaxQueueSize() { + return maxQueueSize; + } + + public void setMaxQueueSize(Integer maxQueueSize) { + this.maxQueueSize = maxQueueSize; + } + + public Integer getQueueSizeRejectionThreshold() { + return queueSizeRejectionThreshold; + } + + public void setQueueSizeRejectionThreshold(Integer queueSizeRejectionThreshold) { + this.queueSizeRejectionThreshold = queueSizeRejectionThreshold; + } + + public Integer getRollingStatisticalWindowInMilliseconds() { + return rollingStatisticalWindowInMilliseconds; + } + + public void setRollingStatisticalWindowInMilliseconds(Integer rollingStatisticalWindowInMilliseconds) { + this.rollingStatisticalWindowInMilliseconds = rollingStatisticalWindowInMilliseconds; + } + + public Integer getRollingStatisticalWindowBuckets() { + return rollingStatisticalWindowBuckets; + } + + public void setRollingStatisticalWindowBuckets(Integer rollingStatisticalWindowBuckets) { + this.rollingStatisticalWindowBuckets = rollingStatisticalWindowBuckets; + } + + public Boolean getCircuitBreakerEnabled() { + return circuitBreakerEnabled; + } + + public void setCircuitBreakerEnabled(Boolean circuitBreakerEnabled) { + this.circuitBreakerEnabled = circuitBreakerEnabled; + } + + public Integer getCircuitBreakerErrorThresholdPercentage() { + return circuitBreakerErrorThresholdPercentage; + } + + public void setCircuitBreakerErrorThresholdPercentage(Integer circuitBreakerErrorThresholdPercentage) { + this.circuitBreakerErrorThresholdPercentage = circuitBreakerErrorThresholdPercentage; + } + + public Boolean getCircuitBreakerForceClosed() { + return circuitBreakerForceClosed; + } + + public void setCircuitBreakerForceClosed(Boolean circuitBreakerForceClosed) { + this.circuitBreakerForceClosed = circuitBreakerForceClosed; + } + + public Boolean getCircuitBreakerForceOpen() { + return circuitBreakerForceOpen; + } + + public void setCircuitBreakerForceOpen(Boolean circuitBreakerForceOpen) { + this.circuitBreakerForceOpen = circuitBreakerForceOpen; + } + + public Integer getCircuitBreakerRequestVolumeThreshold() { + return circuitBreakerRequestVolumeThreshold; + } + + public void setCircuitBreakerRequestVolumeThreshold(Integer circuitBreakerRequestVolumeThreshold) { + this.circuitBreakerRequestVolumeThreshold = circuitBreakerRequestVolumeThreshold; + } + + public Integer getCircuitBreakerSleepWindowInMilliseconds() { + return circuitBreakerSleepWindowInMilliseconds; + } + + public void setCircuitBreakerSleepWindowInMilliseconds(Integer circuitBreakerSleepWindowInMilliseconds) { + this.circuitBreakerSleepWindowInMilliseconds = circuitBreakerSleepWindowInMilliseconds; + } + + public Integer getExecutionIsolationSemaphoreMaxConcurrentRequests() { + return executionIsolationSemaphoreMaxConcurrentRequests; + } + + public void setExecutionIsolationSemaphoreMaxConcurrentRequests(Integer executionIsolationSemaphoreMaxConcurrentRequests) { + this.executionIsolationSemaphoreMaxConcurrentRequests = executionIsolationSemaphoreMaxConcurrentRequests; + } + + public String getExecutionIsolationStrategy() { + return executionIsolationStrategy; + } + + public void setExecutionIsolationStrategy(String executionIsolationStrategy) { + this.executionIsolationStrategy = executionIsolationStrategy; + } + + public Boolean getExecutionIsolationThreadInterruptOnTimeout() { + return executionIsolationThreadInterruptOnTimeout; + } + + public void setExecutionIsolationThreadInterruptOnTimeout(Boolean executionIsolationThreadInterruptOnTimeout) { + this.executionIsolationThreadInterruptOnTimeout = executionIsolationThreadInterruptOnTimeout; + } + + public Integer getExecutionTimeoutInMilliseconds() { + return executionTimeoutInMilliseconds; + } + + public void setExecutionTimeoutInMilliseconds(Integer executionTimeoutInMilliseconds) { + this.executionTimeoutInMilliseconds = executionTimeoutInMilliseconds; + } + + public Boolean getExecutionTimeoutEnabled() { + return executionTimeoutEnabled; + } + + public void setExecutionTimeoutEnabled(Boolean executionTimeoutEnabled) { + this.executionTimeoutEnabled = executionTimeoutEnabled; + } + + public Integer getFallbackIsolationSemaphoreMaxConcurrentRequests() { + return fallbackIsolationSemaphoreMaxConcurrentRequests; + } + + public void setFallbackIsolationSemaphoreMaxConcurrentRequests(Integer fallbackIsolationSemaphoreMaxConcurrentRequests) { + this.fallbackIsolationSemaphoreMaxConcurrentRequests = fallbackIsolationSemaphoreMaxConcurrentRequests; + } + + public Boolean getFallbackEnabled() { + return fallbackEnabled; + } + + public void setFallbackEnabled(Boolean fallbackEnabled) { + this.fallbackEnabled = fallbackEnabled; + } + + public Integer getMetricsHealthSnapshotIntervalInMilliseconds() { + return metricsHealthSnapshotIntervalInMilliseconds; + } + + public void setMetricsHealthSnapshotIntervalInMilliseconds(Integer metricsHealthSnapshotIntervalInMilliseconds) { + this.metricsHealthSnapshotIntervalInMilliseconds = metricsHealthSnapshotIntervalInMilliseconds; + } + + public Integer getMetricsRollingPercentileBucketSize() { + return metricsRollingPercentileBucketSize; + } + + public void setMetricsRollingPercentileBucketSize(Integer metricsRollingPercentileBucketSize) { + this.metricsRollingPercentileBucketSize = metricsRollingPercentileBucketSize; + } + + public Boolean getMetricsRollingPercentileEnabled() { + return metricsRollingPercentileEnabled; + } + + public void setMetricsRollingPercentileEnabled(Boolean metricsRollingPercentileEnabled) { + this.metricsRollingPercentileEnabled = metricsRollingPercentileEnabled; + } + + public Integer getMetricsRollingPercentileWindowInMilliseconds() { + return metricsRollingPercentileWindowInMilliseconds; + } + + public void setMetricsRollingPercentileWindowInMilliseconds(Integer metricsRollingPercentileWindowInMilliseconds) { + this.metricsRollingPercentileWindowInMilliseconds = metricsRollingPercentileWindowInMilliseconds; + } + + public Integer getMetricsRollingPercentileWindowBuckets() { + return metricsRollingPercentileWindowBuckets; + } + + public void setMetricsRollingPercentileWindowBuckets(Integer metricsRollingPercentileWindowBuckets) { + this.metricsRollingPercentileWindowBuckets = metricsRollingPercentileWindowBuckets; + } + + public Integer getMetricsRollingStatisticalWindowInMilliseconds() { + return metricsRollingStatisticalWindowInMilliseconds; + } + + public void setMetricsRollingStatisticalWindowInMilliseconds(Integer metricsRollingStatisticalWindowInMilliseconds) { + this.metricsRollingStatisticalWindowInMilliseconds = metricsRollingStatisticalWindowInMilliseconds; + } + + public Integer getMetricsRollingStatisticalWindowBuckets() { + return metricsRollingStatisticalWindowBuckets; + } + + public void setMetricsRollingStatisticalWindowBuckets(Integer metricsRollingStatisticalWindowBuckets) { + this.metricsRollingStatisticalWindowBuckets = metricsRollingStatisticalWindowBuckets; + } + + public Boolean getRequestCacheEnabled() { + return requestCacheEnabled; + } + + public void setRequestCacheEnabled(Boolean requestCacheEnabled) { + this.requestCacheEnabled = requestCacheEnabled; + } + + public Boolean getRequestLogEnabled() { + return requestLogEnabled; + } + + public void setRequestLogEnabled(Boolean requestLogEnabled) { + this.requestLogEnabled = requestLogEnabled; + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixConstants.java ---------------------------------------------------------------------- diff --git a/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixConstants.java b/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixConstants.java new file mode 100644 index 0000000..33ba6d4 --- /dev/null +++ b/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixConstants.java @@ -0,0 +1,22 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.hystrix; + +public interface HystrixConstants { + String CAMEL_HYSTRIX_REQUEST_CONTEXT_KEY = "CamelHystrixRequestContextKey"; + String CAMEL_HYSTRIX_CLEAR_CACHE_FIRST = "CamelHystrixClearCacheFirst"; +} http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixEndpoint.java ---------------------------------------------------------------------- diff --git a/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixEndpoint.java b/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixEndpoint.java new file mode 100644 index 0000000..2baa16c --- /dev/null +++ b/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixEndpoint.java @@ -0,0 +1,88 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.hystrix; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import com.netflix.hystrix.Hystrix; +import com.netflix.hystrix.HystrixThreadPoolKey; +import com.netflix.hystrix.strategy.HystrixPlugins; +import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; +import com.netflix.hystrix.strategy.properties.HystrixProperty; +import org.apache.camel.Consumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.impl.DefaultEndpoint; +import org.apache.camel.spi.UriEndpoint; +import org.apache.camel.spi.UriParam; + +/** + * Represents a Hystrix endpoint. + */ +@UriEndpoint(scheme = "hystrix", title = "Hystrix", syntax = "hystrix:groupKey", producerOnly = true, label = "scheduling,concurrency") +public class HystrixEndpoint extends DefaultEndpoint { + + @UriParam + private HystrixConfiguration configuration; + + public HystrixEndpoint(String uri, HystrixComponent component, HystrixConfiguration configuration) { + super(uri, component); + this.configuration = configuration; + } + + public Producer createProducer() throws Exception { + return new HystrixProducer(this, configuration); + } + + public Consumer createConsumer(Processor processor) throws Exception { + throw new UnsupportedOperationException("Consumer not supported for Hystrix endpoint"); + } + + public boolean isSingleton() { + return true; + } + + @Override + protected void doStop() throws Exception { + Hystrix.reset(); + HystrixPlugins.getInstance().reset(); + super.doStop(); + } + + @Override + protected void doStart() throws Exception { + HystrixPlugins.getInstance().registerConcurrencyStrategy(new HystrixConcurrencyStrategy() { + + @Override + public ThreadPoolExecutor getThreadPool(final HystrixThreadPoolKey threadPoolKey, + HystrixProperty<Integer> corePoolSize, HystrixProperty<Integer> maximumPoolSize, + HystrixProperty<Integer> keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { + return new ThreadPoolExecutor(corePoolSize.get(), maximumPoolSize.get(), keepAliveTime.get(), unit, workQueue, new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + return getCamelContext().getExecutorServiceManager().newThread("camel-hystrix-" + threadPoolKey.name(), r); + } + }); + } + }); + + super.doStart(); + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixProducer.java ---------------------------------------------------------------------- diff --git a/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixProducer.java b/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixProducer.java new file mode 100644 index 0000000..bafe5c7 --- /dev/null +++ b/components/camel-hystrix/src/main/java/org/apache/camel/component/hystrix/HystrixProducer.java @@ -0,0 +1,233 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.hystrix; + +import com.netflix.hystrix.HystrixCommand; +import com.netflix.hystrix.HystrixCommandGroupKey; +import com.netflix.hystrix.HystrixCommandKey; +import com.netflix.hystrix.HystrixCommandProperties; +import com.netflix.hystrix.HystrixRequestCache; +import com.netflix.hystrix.HystrixThreadPoolKey; +import com.netflix.hystrix.HystrixThreadPoolProperties; +import com.netflix.hystrix.strategy.HystrixPlugins; +import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultProducer; + +/** + * The Hystrix producer. + */ +public class HystrixProducer extends DefaultProducer { + private HystrixConfiguration configuration; + private HystrixRequestContext requestContext; + + public HystrixProducer(HystrixEndpoint endpoint, HystrixConfiguration configuration) { + super(endpoint); + this.configuration = configuration; + } + + public void process(final Exchange exchange) throws Exception { + HystrixCommand.Setter setter = HystrixCommand.Setter.withGroupKey( + HystrixCommandGroupKey.Factory.asKey(configuration.getGroupKey())); + setCommandPropertiesDefaults(setter); + setThreadPoolPropertiesDefaults(setter); + + CamelHystrixCommand camelHystrixCommand = new CamelHystrixCommand(setter, exchange, getCacheKey(exchange), + configuration.getRunEndpointId(), configuration.getFallbackEndpointId()); + + checkRequestContextPresent(exchange); + clearCache(camelHystrixCommand.getCommandKey(), exchange); + camelHystrixCommand.execute(); + } + + private void setCommandPropertiesDefaults(HystrixCommand.Setter setter) { + if (configuration.getCommandKey() != null) { + setter.andCommandKey(HystrixCommandKey.Factory.asKey(configuration.getCommandKey())); + } + + HystrixCommandProperties.Setter commandDefaults = HystrixCommandProperties.Setter(); + setter.andCommandPropertiesDefaults(commandDefaults); + + if (configuration.getCircuitBreakerEnabled() != null) { + commandDefaults.withCircuitBreakerEnabled(configuration.getCircuitBreakerEnabled()); + } + + if (configuration.getCircuitBreakerErrorThresholdPercentage() != null) { + commandDefaults.withCircuitBreakerErrorThresholdPercentage( + configuration.getCircuitBreakerErrorThresholdPercentage()); + } + + if (configuration.getCircuitBreakerForceClosed() != null) { + commandDefaults.withCircuitBreakerForceClosed(configuration.getCircuitBreakerForceClosed()); + } + + if (configuration.getCircuitBreakerForceOpen() != null) { + commandDefaults.withCircuitBreakerForceOpen(configuration.getCircuitBreakerForceOpen()); + } + + if (configuration.getCircuitBreakerRequestVolumeThreshold() != null) { + commandDefaults.withCircuitBreakerRequestVolumeThreshold( + configuration.getCircuitBreakerRequestVolumeThreshold()); + } + + if (configuration.getCircuitBreakerSleepWindowInMilliseconds() != null) { + commandDefaults.withCircuitBreakerSleepWindowInMilliseconds( + configuration.getCircuitBreakerSleepWindowInMilliseconds()); + } + + if (configuration.getExecutionIsolationSemaphoreMaxConcurrentRequests() != null) { + commandDefaults.withExecutionIsolationSemaphoreMaxConcurrentRequests( + configuration.getExecutionIsolationSemaphoreMaxConcurrentRequests()); + } + + if (configuration.getExecutionIsolationStrategy() != null) { + commandDefaults.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.valueOf( + configuration.getExecutionIsolationStrategy())); + } + + if (configuration.getExecutionIsolationThreadInterruptOnTimeout() != null) { + commandDefaults.withExecutionIsolationThreadInterruptOnTimeout( + configuration.getExecutionIsolationThreadInterruptOnTimeout()); + } + + if (configuration.getExecutionTimeoutInMilliseconds() != null) { + commandDefaults.withExecutionTimeoutInMilliseconds(configuration.getExecutionTimeoutInMilliseconds()); + } + + if (configuration.getExecutionTimeoutEnabled() != null) { + commandDefaults.withExecutionTimeoutEnabled(configuration.getExecutionTimeoutEnabled()); + } + + if (configuration.getFallbackIsolationSemaphoreMaxConcurrentRequests() != null) { + commandDefaults.withFallbackIsolationSemaphoreMaxConcurrentRequests( + configuration.getFallbackIsolationSemaphoreMaxConcurrentRequests()); + } + + if (configuration.getFallbackEnabled() != null) { + commandDefaults.withFallbackEnabled(configuration.getFallbackEnabled()); + } + if (configuration.getMetricsHealthSnapshotIntervalInMilliseconds() != null) { + commandDefaults.withMetricsHealthSnapshotIntervalInMilliseconds(configuration.getMetricsHealthSnapshotIntervalInMilliseconds()); + } + + if (configuration.getMetricsRollingPercentileBucketSize() != null) { + commandDefaults.withMetricsRollingPercentileBucketSize(configuration.getMetricsRollingPercentileBucketSize()); + } + + if (configuration.getMetricsRollingPercentileEnabled() != null) { + commandDefaults.withMetricsRollingPercentileEnabled(configuration.getMetricsRollingPercentileEnabled()); + } + + if (configuration.getMetricsRollingPercentileWindowInMilliseconds() != null) { + commandDefaults.withMetricsRollingPercentileWindowInMilliseconds(configuration.getMetricsRollingPercentileWindowInMilliseconds()); + } + + if (configuration.getMetricsRollingPercentileWindowBuckets() != null) { + commandDefaults.withMetricsRollingPercentileWindowBuckets(configuration.getMetricsRollingPercentileWindowBuckets()); + } + + if (configuration.getMetricsRollingStatisticalWindowInMilliseconds() != null) { + commandDefaults.withMetricsRollingStatisticalWindowInMilliseconds(configuration.getMetricsRollingStatisticalWindowInMilliseconds()); + } + + if (configuration.getMetricsRollingStatisticalWindowBuckets() != null) { + commandDefaults.withMetricsRollingStatisticalWindowBuckets(configuration.getMetricsRollingStatisticalWindowBuckets()); + } + + if (configuration.getRequestCacheEnabled() != null) { + commandDefaults.withRequestCacheEnabled(configuration.getRequestCacheEnabled()); + } + + if (configuration.getRequestLogEnabled() != null) { + commandDefaults.withRequestLogEnabled(configuration.getRequestLogEnabled()); + } + } + + private void setThreadPoolPropertiesDefaults(HystrixCommand.Setter setter) { + if (configuration.getThreadPoolKey() != null) { + setter.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(configuration.getThreadPoolKey())); + } + + HystrixThreadPoolProperties.Setter threadPoolProperties = HystrixThreadPoolProperties.Setter(); + setter.andThreadPoolPropertiesDefaults(threadPoolProperties); + + if (configuration.getCoreSize() != null) { + threadPoolProperties.withCoreSize(configuration.getCoreSize()); + } + if (configuration.getKeepAliveTimeMinutes() != null) { + threadPoolProperties.withKeepAliveTimeMinutes(configuration.getKeepAliveTimeMinutes()); + } + if (configuration.getMaxQueueSize() != null) { + threadPoolProperties.withMaxQueueSize(configuration.getMaxQueueSize()); + } + if (configuration.getQueueSizeRejectionThreshold() != null) { + threadPoolProperties.withQueueSizeRejectionThreshold(configuration.getQueueSizeRejectionThreshold()); + } + if (configuration.getMetricsRollingStatisticalWindowInMilliseconds() != null) { + threadPoolProperties.withMetricsRollingStatisticalWindowInMilliseconds( + configuration.getMetricsRollingStatisticalWindowInMilliseconds()); + } + if (configuration.getMetricsRollingStatisticalWindowBuckets() != null) { + threadPoolProperties.withMetricsRollingStatisticalWindowBuckets( + configuration.getMetricsRollingStatisticalWindowBuckets()); + } + } + + private String getCacheKey(Exchange exchange) { + return configuration.getCacheKeyExpression() != null + ? configuration.getCacheKeyExpression().evaluate(exchange, String.class) : null; + } + + private synchronized void checkRequestContextPresent(Exchange exchange) { + if (!HystrixRequestContext.isCurrentThreadInitialized()) { + HystrixRequestContext customRequestContext = exchange.getIn() + .getHeader(HystrixConstants.CAMEL_HYSTRIX_REQUEST_CONTEXT_KEY, HystrixRequestContext.class); + + if (customRequestContext != null) { + HystrixRequestContext.setContextOnCurrentThread(customRequestContext); + } else { + HystrixRequestContext.setContextOnCurrentThread(requestContext); + exchange.getIn().setHeader(HystrixConstants.CAMEL_HYSTRIX_REQUEST_CONTEXT_KEY, requestContext); + } + } + } + + private void clearCache(HystrixCommandKey camelHystrixCommand, Exchange exchange) { + Boolean clearCache = exchange.getIn().getHeader(HystrixConstants.CAMEL_HYSTRIX_CLEAR_CACHE_FIRST, Boolean.class); + if (clearCache != null && clearCache) { + HystrixRequestCache.getInstance(camelHystrixCommand, + HystrixPlugins.getInstance().getConcurrencyStrategy()).clear(String.valueOf(getCacheKey(exchange))); + } + } + + @Override + protected void doStart() throws Exception { + if (configuration.getPropagateRequestContext() != null && configuration.getPropagateRequestContext()) { + requestContext = HystrixRequestContext.initializeContext(); + } + super.doStart(); + } + + @Override + protected void doStop() throws Exception { + if (requestContext != null) { + requestContext.shutdown(); + } + super.doStop(); + } + +} http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/components/camel-hystrix/src/main/resources/META-INF/LICENSE.txt ---------------------------------------------------------------------- diff --git a/components/camel-hystrix/src/main/resources/META-INF/LICENSE.txt b/components/camel-hystrix/src/main/resources/META-INF/LICENSE.txt new file mode 100644 index 0000000..6b0b127 --- /dev/null +++ b/components/camel-hystrix/src/main/resources/META-INF/LICENSE.txt @@ -0,0 +1,203 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/components/camel-hystrix/src/main/resources/META-INF/NOTICE.txt ---------------------------------------------------------------------- diff --git a/components/camel-hystrix/src/main/resources/META-INF/NOTICE.txt b/components/camel-hystrix/src/main/resources/META-INF/NOTICE.txt new file mode 100644 index 0000000..2e215bf --- /dev/null +++ b/components/camel-hystrix/src/main/resources/META-INF/NOTICE.txt @@ -0,0 +1,11 @@ + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Apache Camel distribution. == + ========================================================================= + + This product includes software developed by + The Apache Software Foundation (http://www.apache.org/). + + Please read the different LICENSE files present in the licenses directory of + this distribution. http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/components/camel-hystrix/src/main/resources/META-INF/services/org/apache/camel/component/hystrix ---------------------------------------------------------------------- diff --git a/components/camel-hystrix/src/main/resources/META-INF/services/org/apache/camel/component/hystrix b/components/camel-hystrix/src/main/resources/META-INF/services/org/apache/camel/component/hystrix new file mode 100644 index 0000000..8fc3ece --- /dev/null +++ b/components/camel-hystrix/src/main/resources/META-INF/services/org/apache/camel/component/hystrix @@ -0,0 +1,18 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +class=org.apache.camel.component.hystrix.HystrixComponent http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/components/camel-hystrix/src/test/java/org/apache/camel/component/hystrix/HystrixComponentCircuitBreakerTest.java ---------------------------------------------------------------------- diff --git a/components/camel-hystrix/src/test/java/org/apache/camel/component/hystrix/HystrixComponentCircuitBreakerTest.java b/components/camel-hystrix/src/test/java/org/apache/camel/component/hystrix/HystrixComponentCircuitBreakerTest.java new file mode 100644 index 0000000..ab11518 --- /dev/null +++ b/components/camel-hystrix/src/test/java/org/apache/camel/component/hystrix/HystrixComponentCircuitBreakerTest.java @@ -0,0 +1,100 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.hystrix; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.Produce; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.builder.ExpressionBuilder; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.impl.SimpleRegistry; +import org.apache.camel.test.junit4.CamelTestSupport; +import org.junit.Test; + +public class HystrixComponentCircuitBreakerTest extends CamelTestSupport { + + @Produce(uri = "direct:start") + protected ProducerTemplate template; + + @EndpointInject(uri = "mock:result") + protected MockEndpoint resultEndpoint; + + @EndpointInject(uri = "mock:error") + protected MockEndpoint errorEndpoint; + + @Test + public void circuitBreakerRejectsWhenTresholdReached() throws Exception { + final int requestCount = 5; + resultEndpoint.expectedMessageCount(2); + errorEndpoint.expectedMessageCount(requestCount); + resultEndpoint.whenAnyExchangeReceived(new Processor() { + @Override + public void process(Exchange exchange) throws Exception { + throw new RuntimeException("blow"); + } + }); + + for (int i = 0; i < requestCount; i++) { + try { + template.sendBody("test"); + } catch (Exception e) { + + } + } + assertMockEndpointsSatisfied(); + } + + @Override + protected CamelContext createCamelContext() throws Exception { + SimpleRegistry registry = new SimpleRegistry(); + CamelContext context = new DefaultCamelContext(registry); + registry.put("run", context.getEndpoint("direct:run")); + registry.put("fallback", context.getEndpoint("direct:fallback")); + registry.put("headerExpression", ExpressionBuilder.headerExpression("key")); + return context; + } + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + + public void configure() { + + from("direct:fallback") + .to("mock:error"); + + from("direct:run") + .process(new Processor() { + @Override + public void process(Exchange exchange) throws Exception { + Thread.sleep(500); + } + }) + .to("mock:result"); + + from("direct:start") + .to("hystrix:testKey?runEndpointId=run&fallbackEndpointId=fallback&circuitBreakerRequestVolumeThreshold=2"); + } + }; + } +} + http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/components/camel-hystrix/src/test/java/org/apache/camel/component/hystrix/HystrixComponentRequestContextTest.java ---------------------------------------------------------------------- diff --git a/components/camel-hystrix/src/test/java/org/apache/camel/component/hystrix/HystrixComponentRequestContextTest.java b/components/camel-hystrix/src/test/java/org/apache/camel/component/hystrix/HystrixComponentRequestContextTest.java new file mode 100644 index 0000000..9286373 --- /dev/null +++ b/components/camel-hystrix/src/test/java/org/apache/camel/component/hystrix/HystrixComponentRequestContextTest.java @@ -0,0 +1,120 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.hystrix; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.Produce; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.builder.ExpressionBuilder; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.impl.SimpleRegistry; +import org.apache.camel.test.junit4.CamelTestSupport; +import org.junit.Test; + +public class HystrixComponentRequestContextTest extends CamelTestSupport { + + @Produce(uri = "direct:start") + protected ProducerTemplate template; + + @EndpointInject(uri = "mock:result") + protected MockEndpoint resultEndpoint; + + @EndpointInject(uri = "mock:error") + protected MockEndpoint errorEndpoint; + + @Test + public void invokesCachedEndpointWithCustomRequestContext() throws Exception { + resultEndpoint.expectedMessageCount(1); + errorEndpoint.expectedMessageCount(0); + + HystrixRequestContext customContext = HystrixRequestContext.initializeContext(); + final Map headers = new HashMap<>(); + headers.put("key", "cachedKey"); + headers.put(HystrixConstants.CAMEL_HYSTRIX_REQUEST_CONTEXT_KEY, customContext); + + template.sendBodyAndHeaders("body", headers); + + final CountDownLatch latch = new CountDownLatch(1); + new Thread(new Runnable() { + @Override + public void run() { + template.sendBodyAndHeaders("body", headers); + latch.countDown(); + } + }).start(); + + latch.await(2, TimeUnit.SECONDS); + + assertMockEndpointsSatisfied(); + } + + @Test + public void invokesCachedEndpointTwiceWhenCacheIsCleared() throws Exception { + resultEndpoint.expectedMessageCount(2); + errorEndpoint.expectedMessageCount(0); + + HystrixRequestContext customContext = HystrixRequestContext.initializeContext(); + final Map headers = new HashMap<>(); + headers.put("key", "cachedKey"); + headers.put(HystrixConstants.CAMEL_HYSTRIX_REQUEST_CONTEXT_KEY, customContext); + + template.sendBodyAndHeaders("body", headers); + + headers.put(HystrixConstants.CAMEL_HYSTRIX_CLEAR_CACHE_FIRST, true); + + template.sendBodyAndHeaders("body", headers); + assertMockEndpointsSatisfied(); + } + + @Override + protected CamelContext createCamelContext() throws Exception { + SimpleRegistry registry = new SimpleRegistry(); + CamelContext context = new DefaultCamelContext(registry); + registry.put("run", context.getEndpoint("direct:run")); + registry.put("fallback", context.getEndpoint("direct:fallback")); + registry.put("headerExpression", ExpressionBuilder.headerExpression("key")); + return context; + } + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + + public void configure() { + + from("direct:fallback") + .to("mock:error"); + + from("direct:run") + .to("mock:result"); + + from("direct:start") + .to("hystrix:testKey?runEndpointId=run&fallbackEndpointId=fallback&cacheKeyExpression=#headerExpression"); + } + }; + } +} + http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/components/camel-hystrix/src/test/java/org/apache/camel/component/hystrix/HystrixComponentTest.java ---------------------------------------------------------------------- diff --git a/components/camel-hystrix/src/test/java/org/apache/camel/component/hystrix/HystrixComponentTest.java b/components/camel-hystrix/src/test/java/org/apache/camel/component/hystrix/HystrixComponentTest.java new file mode 100644 index 0000000..f3b3739 --- /dev/null +++ b/components/camel-hystrix/src/test/java/org/apache/camel/component/hystrix/HystrixComponentTest.java @@ -0,0 +1,154 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.hystrix; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.Produce; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.builder.ExpressionBuilder; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.impl.SimpleRegistry; +import org.apache.camel.test.junit4.CamelTestSupport; +import org.junit.Test; + +public class HystrixComponentTest extends CamelTestSupport { + + @Produce(uri = "direct:start") + protected ProducerTemplate template; + + @EndpointInject(uri = "mock:result") + protected MockEndpoint resultEndpoint; + + @EndpointInject(uri = "mock:error") + protected MockEndpoint errorEndpoint; + + @Test + public void invokesTargetEndpoint() throws Exception { + resultEndpoint.expectedMessageCount(1); + errorEndpoint.expectedMessageCount(0); + + template.sendBody("test"); + + assertMockEndpointsSatisfied(); + } + + @Test + public void invokesFallbackEndpointExceptionThrown() throws Exception { + resultEndpoint.expectedMessageCount(1); + errorEndpoint.expectedMessageCount(1); + resultEndpoint.whenAnyExchangeReceived(new Processor() { + @Override + public void process(Exchange exchange) throws Exception { + throw new RuntimeException("blow"); + } + }); + + template.sendBody("test"); + + assertMockEndpointsSatisfied(); + } + + @Test + public void invokesFallbackEndpointExceptionSet() throws Exception { + resultEndpoint.expectedMessageCount(1); + errorEndpoint.expectedMessageCount(1); + resultEndpoint.whenAnyExchangeReceived(new Processor() { + @Override + public void process(Exchange exchange) throws Exception { + exchange.setException(new RuntimeException("blow")); + } + }); + + template.sendBody("test"); + + assertMockEndpointsSatisfied(); + } + + @Test + public void invokesCachedEndpoint() throws Exception { + resultEndpoint.expectedMessageCount(1); + errorEndpoint.expectedMessageCount(0); + + template.sendBodyAndHeader("body", "key", "cachedKey"); + template.sendBodyAndHeader("body", "key", "cachedKey"); + + assertMockEndpointsSatisfied(); + + resultEndpoint.expectedMessageCount(2); + template.sendBodyAndHeader("body", "key", "cachedKey"); + template.sendBodyAndHeader("body", "key", "differentCachedKey"); + assertMockEndpointsSatisfied(); + } + + @Test + public void invokesCachedEndpointFromDifferentThread() throws Exception { + resultEndpoint.expectedMessageCount(1); + errorEndpoint.expectedMessageCount(0); + + template.sendBodyAndHeader("body", "key", "cachedKey"); + + final CountDownLatch latch = new CountDownLatch(1); + new Thread(new Runnable() { + @Override + public void run() { + template.sendBodyAndHeader("body", "key", "cachedKey"); + latch.countDown(); + } + }).start(); + + latch.await(2, TimeUnit.SECONDS); + + assertMockEndpointsSatisfied(); + } + + @Override + protected CamelContext createCamelContext() throws Exception { + SimpleRegistry registry = new SimpleRegistry(); + CamelContext context = new DefaultCamelContext(registry); + registry.put("run", context.getEndpoint("direct:run")); + registry.put("fallback", context.getEndpoint("direct:fallback")); + registry.put("bodyExpression", ExpressionBuilder.headerExpression("key")); + return context; + } + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + + public void configure() { + + from("direct:fallback") + .to("mock:error"); + + from("direct:run") + .to("mock:result"); + + from("direct:start") + .to("hystrix:testKey?runEndpointId=run&fallbackEndpointId=fallback&cacheKeyExpression=#bodyExpression&propagateRequestContext=true"); + } + }; + } +} + http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/components/camel-hystrix/src/test/resources/log4j.properties ---------------------------------------------------------------------- diff --git a/components/camel-hystrix/src/test/resources/log4j.properties b/components/camel-hystrix/src/test/resources/log4j.properties new file mode 100644 index 0000000..1f3f02a --- /dev/null +++ b/components/camel-hystrix/src/test/resources/log4j.properties @@ -0,0 +1,36 @@ +## ------------------------------------------------------------------------ +## Licensed to the Apache Software Foundation (ASF) under one or more +## contributor license agreements. See the NOTICE file distributed with +## this work for additional information regarding copyright ownership. +## The ASF licenses this file to You under the Apache License, Version 2.0 +## (the "License"); you may not use this file except in compliance with +## the License. You may obtain a copy of the License at +## +## http://www.apache.org/licenses/LICENSE-2.0 +## +## Unless required by applicable law or agreed to in writing, software +## distributed under the License is distributed on an "AS IS" BASIS, +## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +## See the License for the specific language governing permissions and +## limitations under the License. +## ------------------------------------------------------------------------ + +# +# The logging properties used for testing. +# +log4j.rootLogger=DEBUG, out + +# uncomment the following to enable camel debugging +#log4j.logger.org.apache.camel.component.hystrix=DEBUG + +# CONSOLE appender not used by default +log4j.appender.out=org.apache.log4j.ConsoleAppender +log4j.appender.out.layout=org.apache.log4j.PatternLayout +#log4j.appender.out.layout.ConversionPattern=[%30.30t] %-30.30c{1} %-5p %m%n +log4j.appender.out.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n + +# File appender +log4j.appender.file=org.apache.log4j.FileAppender +log4j.appender.file.layout=org.apache.log4j.PatternLayout +log4j.appender.file.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n +log4j.appender.file.file=target/camel-hystrix-test.log http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/components/pom.xml ---------------------------------------------------------------------- diff --git a/components/pom.xml b/components/pom.xml index 35f5a8b..1e86994 100644 --- a/components/pom.xml +++ b/components/pom.xml @@ -49,6 +49,7 @@ <module>camel-http-common</module> <module>camel-http</module> <module>camel-http4</module> + <module>camel-hystrix</module> <module>camel-jetty-common</module> <module>camel-jetty</module> <module>camel-jetty8</module> http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/parent/pom.xml ---------------------------------------------------------------------- diff --git a/parent/pom.xml b/parent/pom.xml index e8768ed..688d662 100644 --- a/parent/pom.xml +++ b/parent/pom.xml @@ -241,6 +241,8 @@ <httpclient4-olingo2-version>4.4.1</httpclient4-olingo2-version> <httpasyncclient-version>4.1.1</httpasyncclient-version> <httpclient-version>3.1</httpclient-version> + <hystrix-version>1.4.23</hystrix-version> + <hystrix-bundle-version>1.3.13_1</hystrix-bundle-version> <ibatis-bundle-version>2.3.4.726_4</ibatis-bundle-version> <ibatis-version>2.3.4.726</ibatis-version> <ical4j-version>1.0.7</ical4j-version> @@ -1061,6 +1063,11 @@ </dependency> <dependency> <groupId>org.apache.camel</groupId> + <artifactId>camel-hystrix</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.apache.camel</groupId> <artifactId>camel-ibatis</artifactId> <version>${project.version}</version> </dependency> http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/platforms/karaf/features/src/main/resources/bundles.properties ---------------------------------------------------------------------- diff --git a/platforms/karaf/features/src/main/resources/bundles.properties b/platforms/karaf/features/src/main/resources/bundles.properties index cf535c1..affa23a 100644 --- a/platforms/karaf/features/src/main/resources/bundles.properties +++ b/platforms/karaf/features/src/main/resources/bundles.properties @@ -44,6 +44,7 @@ org.apache.servicemix.bundles/org.apache.servicemix.bundles.fop/${fop-bundle-ver org.apache.servicemix.bundles/org.apache.servicemix.bundles.freemarker/${freemarker-bundle-version}/jar org.apache.servicemix.bundles/org.apache.servicemix.bundles.hamcrest/${hamcrest-bundle-version}/jar org.apache.servicemix.bundles/org.apache.servicemix.bundles.hapi/${hapi-bundle-version}/jar +org.apache.servicemix.bundles/org.apache.servicemix.bundles.hystrix/${hystrix-bundle-version}/jar org.apache.servicemix.bundles/org.apache.servicemix.bundles.ibatis-sqlmap/${ibatis-bundle-version}/jar org.apache.servicemix.bundles/org.apache.servicemix.bundles.irclib/${irclib-bundle-version}/jar org.apache.servicemix.bundles/org.apache.servicemix.bundles.isorelax/${isorelax-bundle-version}/jar http://git-wip-us.apache.org/repos/asf/camel/blob/4261f112/platforms/karaf/features/src/main/resources/features.xml ---------------------------------------------------------------------- diff --git a/platforms/karaf/features/src/main/resources/features.xml b/platforms/karaf/features/src/main/resources/features.xml index df02687..5bbae10 100644 --- a/platforms/karaf/features/src/main/resources/features.xml +++ b/platforms/karaf/features/src/main/resources/features.xml @@ -726,6 +726,11 @@ <bundle>mvn:org.apache.camel/camel-http-common/${project.version}</bundle> <bundle>mvn:org.apache.camel/camel-http4/${project.version}</bundle> </feature> + <feature name='camel-hystrix' version='${project.version}' resolver='(obr)' start-level='50'> + <feature version='${project.version}'>camel-core</feature> + <bundle dependency='true'>mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.hystrix/${hystrix-bundle-version}</bundle> + <bundle>mvn:org.apache.camel/camel-hystrix/${project.version}</bundle> + </feature> <feature name='camel-ibatis' version='${project.version}' resolver='(obr)' start-level='50'> <feature version='${project.version}'>camel-core</feature> <feature>transaction</feature>