跳到主要內容

Apache Camel - Aggregator Hello World

Introduction

Camel Aggregator提供開發人員能夠將大量訊息合成一個的功能。假設你的系統會接受外來通知,並將內容寫進資料庫中;一次連線寫一筆資料會比較快,還是透過一次連線寫入五筆資料快呢? 正常來說,一次連線寫入五筆同屬性資料會是比較快的。它與Throttler的最大區別在於,Throttler限制了client的請求,而Aggregator則是收集起來一次“後送”。因此,如果使用Aggregator,你的程式必需要有對應的處理方式。


我將透過HTTP GET請求/events/{id}做為範例,說明如何使用Aggregator去將單位時間內的請求,以{id}去分組並Aggregate成各別分組訊息。本篇文章中使用到兩個RouteBuilder,分別為RestRouteBuilder與AggregatorGroupRouteBuilder。RestRouteBuilder負責REST核心相關設定,可參考先前文章。接下來直接說明AggregatorGroupRouteBuilder。

(程式碼可參考link)

AggregatorGroupRouteBuilder

package org.tonylin.practice.camel.aggregator;
 
import static com.google.common.base.Preconditions.checkState;
 
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.processor.aggregate.GroupedExchangeAggregationStrategy;
 
public class AggregatorGroupRouteBuilder extends RouteBuilder {
 
	private final static String GET_EVENTS = "GET_EVENTS";
 
	private Object eventHandler;
	private int period = 500;
 
	public AggregatorGroupRouteBuilder(Object eventHandler) {
		this.eventHandler = eventHandler;
 
	}
 
	public void setPeriod(int period) {
		this.period = period;
	}
 
	@Override
	public void configure() throws Exception {
		checkState(eventHandler!=null, "Can't find eventHandler");
 
		rest("/events/{id}").get().route().id(GET_EVENTS)
		.aggregate(new GroupedExchangeAggregationStrategy())
		.header("id")
		.completionInterval(period)
		.bean(eventHandler).endRest();
	}
}

以下是在configure中的幾個重點:

  • aggregate(new GroupedExchangeAggregationStrategy()): 使用GroupedExchangeAggregationStrategy去做aggregate,aggregate的內容為Exchange。如果要加入條件限制,是以Exchange去操作。
  • header(“id”): 與aggregate一起使用,代表以header id去分組。在這範例中,指得就是event id。
  • completionInterval(period): 以每period的單位時間去做aggregate。
  • bean(eventHandler): 請求的處理者,必須要有能力處理aggregate後的訊息。

接下來讓我們透過單元測試展示效果。

Unit Test

測試有兩個目標,testGroupedExchange用以確認aggregate group後的結果,另外一個testCompletionInterval則是確認單位時間設定的作用。以下為程式碼主要結構,主要測試程式碼稍後做說明:

package org.tonylin.practice.camel.aggregator;
 
import static com.google.common.base.Preconditions.checkState;
 
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
 
import org.apache.camel.Exchange;
import org.apache.camel.Handler;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.Test;
import org.tonylin.practice.camel.rest.RestRouteBuilder;
 
public class AggregatorGroupRouteBuilderTest extends CamelTestSupport  {
 
	private RestHandler hander = new RestHandler();
 
	private HttpClient client = HttpClientBuilder.create().build();
 
	@Override
	protected RoutesBuilder[] createRouteBuilders() throws Exception {
		AggregatorGroupRouteBuilder aggregatorGroupRouteBuilder = new AggregatorGroupRouteBuilder(hander);
		aggregatorGroupRouteBuilder.setPeriod(500);
 
		return new RoutesBuilder[] {
				new RestRouteBuilder(),
				aggregatorGroupRouteBuilder
		};
	}
 
	@Test
	public void testGroupedExchange() throws Exception {
		// skip
	}
	@Test
	public void testCompletionInterval() throws Exception {
		// skip
	}
}

此測試中的RestHandler程式碼如下,它會透過GROUPED_EXCHANGE取得aggregator處理後的內容,並根據header id儲存到map中,供測試程式碼做assertion。除此之外,在這裡使用CountDownLatch了去確認有收到預期訊息數量:

public static class RestHandler {
	private Map<String, List<Exchange>> requestData = new ConcurrentHashMap<String, List<Exchange>>();
	private CountDownLatch countDownLatch;
 
	@SuppressWarnings("unchecked")
	@Handler
	public void handle(Exchange exchange) {
		List<Exchange> groupExchanges = exchange.getProperty(Exchange.GROUPED_EXCHANGE, List.class);
		String id = groupExchanges.get(0).getIn().getHeader("id", String.class);
		requestData.put(id, groupExchanges);
 
		if( countDownLatch != null )
			countDownLatch.countDown();
	}
 
	public Map<String, List<Exchange>> getRequestData(){
		return requestData;
	}
 
	public void expectNum(int num) {
		countDownLatch = new CountDownLatch(num);
	}
 
	public void waitCompletion(int timeout) throws InterruptedException {
		checkState(countDownLatch!=null);
		countDownLatch.await(timeout, TimeUnit.MILLISECONDS);
	}
 
	public void clear() {
		requestData.clear();
	}
}

首先讓我說明testGroupedExchange。測試程式碼中,送了四個訊息,其中包含了三組不同id;這樣的請求,我們預期RestHandler中,總共會收到三組訊息,其中id 123那組,應包含兩個訊息:

private HttpResponse requestWithEventId(String id) {
	try {
		HttpGet httpGet = new HttpGet("http://localhost:8080/events/" + id);
		return client.execute(httpGet);
	} catch( Exception e ) {
		throw new RuntimeException(e);
	}
}
 
@Test
public void testGroupedExchange() throws Exception {
	// given request event id
	List<String> eventIds = Arrays.asList("123", "123", "456", "789");
	hander.expectNum(3);
 
	// when
	List<HttpResponse> responses = eventIds.parallelStream().map(this::requestWithEventId).collect(Collectors.toList());
 
	// then
	responses.forEach(response->{
		assertEquals(200, response.getStatusLine().getStatusCode());
	});
 
	hander.waitCompletion(1000);
 
	Map<String, List<Exchange>> requestData = hander.getRequestData();
	assertEquals(3, requestData.size());
	assertEquals(2, requestData.get("123").size());
	assertEquals(1, requestData.get("456").size());
	assertEquals(1, requestData.get("789").size());
}

從上述程式碼中,可以發現hander.waitCompletion(1000)是放在確認response之後;所以client只要將訊息發送到aggregator後,就會拿到response code,並不會等到全部處理結束才回去。 接著是testCompletionInterval。這裡我直接透過請求相同id兩次,並分兩輪送出。這樣做可以確認aggregator有做到根據completionInterval的分批效果:

private void requestTwiceWithId(String id) throws Exception {
	// request event {id} twice
	List<String> eventIds = Arrays.asList(id, id);
	hander.expectNum(1);
	List<HttpResponse> responses = eventIds.parallelStream().map(this::requestWithEventId).collect(Collectors.toList());
	responses.forEach(response->{
		assertEquals(200, response.getStatusLine().getStatusCode());
	});
 
	hander.waitCompletion(1000);
 
	// confirm request result
	Map<String, List<Exchange>> requestData = hander.getRequestData();
	assertEquals(1, requestData.size());
	assertEquals(2, requestData.get("123").size());
 
	// clear first request data
	hander.clear();
	assertTrue(hander.getRequestData().isEmpty());
}
 
@Test
public void testCompletionInterval() throws Exception {
	requestTwiceWithId("123");
	requestTwiceWithId("123");
}

Camel Aggregator其實提供了很多細部操作,你也可以根據自身需求做AggregationStrategy;但時間有限,請容我以後有機會再分享。

Library Info (Gradle Config)

以下是我在寫這篇文章時,所使用的libraries版本:

ext {
	camelVersion='2.23.1'
	nettyAllVersion='4.1.34.Final'
	guavaVersion='27.1-jre'
	log4jVersion='1.2.17'
	slf4jVersion='1.7.26'
	httpClientVersion='4.5.7'
}

dependencies {
    compile group: 'org.apache.camel', name: 'camel-core', version: "$camelVersion"
    compile group: 'org.apache.camel', name: 'camel-netty4-http', version: "$camelVersion"
    compile group: 'org.apache.camel', name: 'camel-http-common', version: "$camelVersion"
    compile group: 'org.apache.camel', name: 'camel-netty4', version: "$camelVersion"
    compile group: 'io.netty', name: 'netty-all', version: "$nettyAllVersion"
    compile group: 'com.google.guava', name: 'guava', version: "$guavaVersion"
    compile group: 'log4j', name: 'log4j', version: "$log4jVersion"
    compile group: 'org.slf4j', name: 'slf4j-api', version: "$slf4jVersion"
    runtime group: 'org.slf4j', name: 'slf4j-log4j12', version: "$slf4jVersion"
    testCompile group: 'org.apache.camel', name: 'camel-test', version: "$camelVersion"
    testCompile group: 'org.apache.httpcomponents', name: 'httpclient', version: "$httpClientVersion"
    testCompile 'junit:junit:4.12'
}

Reference

留言

這個網誌中的熱門文章

Show NIC selection when setting the network command with the device option

 Problem  在answer file中設定網卡名稱後,安裝時會停在以下畫面: 所使用的command參數如下: network --onboot = yes --bootproto =dhcp --ipv6 =auto --device =eth1 Diagnostic Result 這樣的參數,以前試驗過是可以安裝完成的。因此在發生這個問題後,我檢查了它的debug console: 從console得知,eth1可能是沒有連接網路線或者是網路太慢而導致的問題。後來和Ivy再三確認,有問題的是有接網路線的網卡,且問題是發生在activate階段: Solution 我想既然有retry應該就有次數或者timeout限制,因此發現在Anaconda的說明文件中( link ),有提到dhcptimeout這個boot參數。看了一些人的使用範例,應該是可以直接串在isolinux.cfg中,如下: default linux ksdevice = link ip =dhcp ks =cdrom: / ks.cfg dhcptimeout = 90 然而我在RHEL/CentOS 6.7與6.8試驗後都無效。 因此我就拿了顯示的錯誤字串,問問Google大師,想找一下Anaconda source code來看一下。最後找到別人根據Anaconda code修改的版本: link ,關鍵在於setupIfaceStruct函式中的setupIfaceStruct與readNetConfig: setupIfaceStruct: 會在dhcp時設定dhcptimeout。 readNetConfig: 在writeEnabledNetInfo將timeout寫入dhclient config中;在wait_for_iface_activation內會根據timeout做retry。 再來從log與code可以得知,它讀取的檔案是answer file而不是boot command line。因此我接下來的測試,就是在answer file的network command上加入dhcptimeout: network --onboot = yes --bootproto =dhcp --ipv6 =auto --device =eth1 --dhcptimeo

解決RobotFramework從3.1.2升級到3.2.2之後,Choose File突然會整個Hand住的問題

考慮到自動測試環境的維護,我們很久以前就使用java去執行robot framework。前陣子開始處理從3.1.2升級到3.2.2的事情,主要先把明確的runtime語法錯誤與deprecate item處理好,這部分內容可以參考: link 。 直到最近才發現,透過SeleniumLibrary執行Choose File去上傳檔案的動作,會導致測試案例timeout。本篇文章主要分享心路歷程與解決方法,我也送了一條issue給robot framework: link 。 我的環境如下: RobotFramework: 3.2.2 Selenium: 3.141.0 SeleniumLibrary: 3.3.1 Remote Selenium Version: selenium-server-standalone-3.141.59 首先並非所有Choose File的動作都會hang住,有些測試案例是可以執行的,但是上傳一個作業系統ISO檔案一定會發生問題。後來我透過wireshark去比對新舊版本的上傳動作,因為我使用 Remote Selenium ,所以Selenium會先把檔案透過REST API發送到Remote Selenium Server上。從下圖我們可以發現,在3.2.2的最後一個TCP封包,比3.1.2大概少了500個bytes。 於是就開始了我trace code之路。包含SeleniumLibrary產生要送給Remote Selenium Server的request內容,還有HTTP Content-Length的計算,我都確認過沒有問題。 最後發現問題是出在socket API的使用上,就是下圖的這支code: 最後發現可能因為開始使用nio的方式送資料,但沒處理到尚未送完的資料內容,而導致發生問題。加一個loop去做計算就可以解決了。 最後我有把解法提供給robot framework官方,在他們出新的版本之前,我是將改完的_socket.py放在我們自己的Lib底下,好讓我們測試可以正常進行。(shutil.py應該也是為了解某個bug而產生的樣子..)

PostgreSQL - Unattended installation on windows

Introduction 要將別人軟體包裝到自己軟體中,不可或缺的東西就是Unattended installation。以Unattended installation來說,我們可以選擇透過Installer的silent mode安裝,也可以透過把目標軟體做成portable的版本。本篇文章分享這兩種方法,教導大家如何將PostgreSQL透過Unattended installation方式安裝到目標系統成為service。 Note. 本篇以PostgreSQL 10.7為例。 Install with installer Tips 安裝程式或反安裝程式的參數,除了可以直接上官網搜尋Installation User Guide以外,也可以直接使用help參數查詢: postgresql- 10.7 - 2 -windows-x64.exe --help Windows安裝程式主要有EnterpriseDB與BigSQL兩種。BigSQL版本安裝元件是透過網路下載且支援參數不如EnterpriseDB版本多,以我們需求來說,我們傾向於使用EnterpriseDB版本。接下來分享給大家安裝與反安裝方法。 Installation @ echo off set INSTALL_DIR =C:\postgres10 set INSTALLER =postgresql- 10.7 - 2 -windows-x64.exe   rem options for installation set SSMDB_SERVICE =postgresql- 10 set MODE =--unattendedmodeui none --mode unattended   set DB_PASSWD =--superpassword postgres set DB_PORT =--serverport 5432   set SERVICE_NAME =--servicename % SSMDB_SERVICE %   set PREFIX =--prefix "%INSTALL_DIR%" set DATA_DIR =--datadir "%INSTALL_DIR%\data"   set OPTIONS =