前言
首先介紹下在本文出現的幾個比較重要的概念:
函數計算(Function Compute): 函數計算是一個事件驅動的服務,通過函數計算,用戶無需管理服務器等運行情況,只需編寫代碼並上傳。函數計算準備計算資源,並以彈性伸縮的方式運行用戶代碼,而用戶只需根據實際代碼運行所消耗的資源進行付費。函數計算更多信息參考。
Fun: Fun 是一個用於支持 Serverless 應用部署的工具,能幫助您便捷地管理函數計算、API 網關、日誌服務等資源。它通過一個資源配置文件(template.yml),協助您進行開發、構建、部署操作。Fun 的更多文檔參考。
備註: 本文介紹的技巧需要 Fun 版本大於等於 2.10.2。
依賴工具
本項目是在 MacOS 下開發的,涉及到的工具是平臺無關的,對於 Linux 和 Windows 桌面系統應該也同樣適用。在開始本例之前請確保如下工具已經正確的安裝,更新到最新版本,並進行正確的配置。
Fun 和 Fcli 工具依賴於 docker 來模擬本地環境。
對於 MacOS 用戶可以使用 homebrew 進行安裝:
brew cask install docker
brew tap vangie/formula
brew install fun
brew install fcli
Windows 和 Linux 用戶安裝請參考:
- https://github.com/aliyun/fun/blob/master/docs/usage/installation.md
- https://github.com/aliyun/fcli/releases
安裝好後,記得先執行 fun config
初始化一下配置。
注意, 如果你已經安裝過了 fun,確保 fun 的版本在 2.10.2 以上。
$ fun --version
2.10.1
快速開始
初始化
使用 fun init 命令可以快捷地將本模板項目初始化到本地。
fun init vangie/selenium-java-example
安裝依賴
$ fun install
...
本地測試
測試代碼 ChromeDemo 的內容爲:
public class ChromeDemo implements StreamRequestHandler {
public void handleRequest(InputStream inputStream,
OutputStream outputStream,
Context context) throws IOException {
System.setProperty("webdriver.chrome.driver", "/code/chromedriver");
ChromeOptions options = new ChromeOptions();
options.setBinary("/code/headless-chromium");
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-gpu"); // applicable to windows os only
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("--no-sandbox"); // Bypass OS security model
options.addArguments("--headless");
WebDriver driver = new ChromeDriver(options);
driver.get("https://ide.fc.aliyun.com");
outputStream.write(("Page title is: " + driver.getTitle() + "\n").getBytes());
driver.quit();
}
}
本地運行
$ mvn package && fun local invoke selenium
...
FC Invoke Start RequestId: 68c83b4c-b053-479c-9b0e-9503582ccb56
handle user request is com.aliyun.fc.selenium.ChromeDemo::handleRequest
cache is null!
Starting ChromeDriver 2.35.528139 (47ead77cb35ad2a9a83248b292151462a66cd881) on port 20652
Only local connections are allowed.
Mar 05, 2019 11:34:27 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Page title is: 雲端集成開發環境
FC Invoke End RequestId: 68c83b4c-b053-479c-9b0e-9503582ccb56
RequestId: 68c83b4c-b053-479c-9b0e-9503582ccb56 Billed Duration: 5265 ms Memory Size: 1998 MB Max Memory Used: 240 MB
部署
$ mvn package && fun deploy
執行
$ fcli function invoke -s chrome -f selenium
Page title is: 雲端集成開發環境
關於文件尺寸
由於 chromedriver 和 headless-chromium 壓縮後體積已經非常接近 50MB,留給用戶 Jar 的空間非常少,所以另外製作了一個高壓縮比版本,使用壓縮比更高的 brotli 算法進行壓縮,壓縮後的大小爲 32.7MB。然後在運行時使用 initializer 進行解壓,解壓耗時大約爲 3.7 S。https://github.com/vangie/packed-selenium-java-example