{"id":595,"date":"2020-03-13T09:00:43","date_gmt":"2020-03-13T16:00:43","guid":{"rendered":"http:\/\/devblogs.microsoft.com\/cosmosdb\/?p=595"},"modified":"2020-03-31T14:00:31","modified_gmt":"2020-03-31T21:00:31","slug":"create-a-java-azure-cosmos-db-function-trigger-using-visual-studio-code-in-2-minutes","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/cosmosdb\/create-a-java-azure-cosmos-db-function-trigger-using-visual-studio-code-in-2-minutes\/","title":{"rendered":"Create a Java Azure Cosmos DB Function Trigger using Visual Studio Code in 2 minutes!"},"content":{"rendered":"<p>&nbsp;<\/p>\n<p>Creating event sourcing solutions with <a href=\"http:\/\/www.azurecosmosdb.com\">Azure Cosmos DB<\/a> is easy with <a href=\"https:\/\/docs.microsoft.com\/azure\/azure-functions\/functions-create-cosmos-db-triggered-function\">Azure Functions Triggers,<\/a> where you can leverage the <a href=\"https:\/\/docs.microsoft.com\/en-us\/azure\/cosmos-db\/change-feed-processor\" data-linktype=\"relative-path\">Change Feed Processor<\/a>&#8216;s powerful scaling and reliable event detection functionality, without the need to maintain any <a href=\"https:\/\/docs.microsoft.com\/en-us\/azure\/cosmos-db\/change-feed-processor\" data-linktype=\"relative-path\">worker infrastructure<\/a>. You can just focus on your Azure Function&#8217;s logic without worrying about the rest of the event-sourcing pipeline. In this blog, we have some quick how-to videos to get you up and running with Java Cosmos DB Functions Triggers!<\/p>\n<p>If you want to following along, there are some pre-requisites you should have in place:<\/p>\n<ul>\n<li>Ideally a Windows 10 Machine.<\/li>\n<li>Access to an Azure subscription, and an Azure Cosmos DB account &#8211; instructions <a href=\"https:\/\/docs.microsoft.com\/en-us\/azure\/cosmos-db\/create-cosmosdb-resources-portal\">here<\/a>.<\/li>\n<li>Visual Studio Code installed &#8211; instructions <a href=\"https:\/\/code.visualstudio.com\/download\">here<\/a>.<\/li>\n<li>Azure Storage Emulator installed (<strong>make sure this is running<\/strong> before trying to follow the demo) &#8211; instructions <a href=\"https:\/\/docs.microsoft.com\/azure\/storage\/common\/storage-use-emulator\">here.<\/a><\/li>\n<li>The pre-requisites for <a href=\"https:\/\/code.visualstudio.com\/docs\/java\/java-azurefunctions\">Azure Functions in Java with VS Code<\/a>.<\/li>\n<li>Azure Functions Core Tools installed &#8211; instructions <a href=\"https:\/\/code.visualstudio.com\/docs\/java\/java-azurefunctions#_install-the-azure-functions-core-tools\">here<\/a> (also given in the above link as an option).<\/li>\n<\/ul>\n<p>Create an Azure Cosmos DB Functions Trigger in Java with VS Code&#8230; in 2 minutes!<\/p>\n<p>(code shown below)<\/p>\n<p><iframe title=\"Create Azure Cosmos DB Functions Trigger (Java) in 2 minutes!\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/tXCEbrRn9OM?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p>The code used in the video is below:<\/p>\n<pre class=\"lang:default decode:true \">package com.function;\r\n\r\nimport com.microsoft.azure.functions.annotation.*;\r\nimport com.microsoft.azure.functions.*;\r\n\r\n\/**\r\n * Azure Functions in Java with Cosmos DB Trigger.\r\n *\/\r\npublic class Function {\r\n\r\n    @FunctionName(\"cosmosDBMonitor\")\r\n    public void cosmosDbProcessor(\r\n            @CosmosDBTrigger(name = \"items\",\r\n            databaseName = \"database\", collectionName = \"collection1\",\r\n            createLeaseCollectionIfNotExists = true,\r\n            connectionStringSetting = \"AzureCosmosDBConnection\") String[] items,\r\n            final ExecutionContext context) {\r\n                for (String string : items) {\r\n                    System.out.println(string);\r\n                }\r\n        context.getLogger().info(items.length + \"item(s) is\/are changed.\");\r\n    }\r\n}\r\n<\/pre>\n<p>The local.settings.json file should look something like the below:<\/p>\n<pre class=\"lang:default decode:true \">{\r\n  \"IsEncrypted\": false,\r\n  \"Values\": {\r\n    \"AzureWebJobsStorage\": \"UseDevelopmentStorage=true\",\r\n    \"AzureCosmosDBConnection\": \"&lt;PRIMARY CONNECTION STRING for Cosmos DB from Azure Portal&gt;\",\r\n    \"FUNCTIONS_WORKER_RUNTIME\": \"java\"\r\n  }\r\n}\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>Next, you can turn your function into a simple event sourcing solution, which streams updates and inserts from one collection into another, by replacing the code created in the first demo, with the below:<\/p>\n<p>&nbsp;<\/p>\n<pre class=\"lang:default decode:true \">package com.function;\r\n\r\nimport com.microsoft.azure.functions.annotation.*;\r\nimport com.microsoft.azure.cosmosdb.ConnectionMode;\r\nimport com.microsoft.azure.cosmosdb.ConnectionPolicy;\r\nimport com.microsoft.azure.cosmosdb.ConsistencyLevel;\r\nimport com.microsoft.azure.cosmosdb.Document;\r\nimport com.microsoft.azure.cosmosdb.rx.AsyncDocumentClient;\r\nimport com.microsoft.azure.functions.*;\r\n\r\n\/**\r\n * Azure Functions in Java with Cosmos DB Trigger.\r\n *\/\r\npublic class Function {\r\n\r\n    private final String databaseName = \"database\";\r\n    private final String collectionId = \"collection2\";\r\n    private AsyncDocumentClient asyncClient;\r\n    private final String targeturi = System.getenv(\"targeturi\");\r\n    private final String targeturikey = System.getenv(\"targeturikey\");\r\n\r\n    ConnectionPolicy connectionPolicy = new ConnectionPolicy();\r\n\r\n    public Function() {\r\n        asyncClient = new AsyncDocumentClient.Builder().withServiceEndpoint(targeturi)\r\n                .withMasterKeyOrResourceToken(targeturikey).withConnectionPolicy(connectionPolicy)\r\n                .withConsistencyLevel(ConsistencyLevel.Session).build();\r\n\r\n    }\r\n\r\n    @FunctionName(\"cosmosDBMonitor\")\r\n    public void cosmosDbProcessor(\r\n            @CosmosDBTrigger(name = \"items\", databaseName = \"database\", collectionName = \"collection1\", createLeaseCollectionIfNotExists = true, connectionStringSetting = \"AzureCosmosDBConnection\") String[] items,\r\n            final ExecutionContext context) {\r\n        connectionPolicy.setConnectionMode(ConnectionMode.Direct);\r\n        for (String string : items) {\r\n            Document doc = new Document(string);\r\n            asyncClient.createDocument(\"dbs\/\" + databaseName + \"\/colls\/\" + collectionId, doc, null, false).toBlocking().single().getResource();\r\n            System.out.println(\"moved document: \"+string);\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>Your local.settings.json would look something like this (note the targeturi and targeturikey added for the target collection):<\/p>\n<p>&nbsp;<\/p>\n<pre class=\"lang:default decode:true \">{\r\n  \"IsEncrypted\": false,\r\n  \"Values\": {\r\n    \"AzureWebJobsStorage\": \"UseDevelopmentStorage=true\",\r\n    \"AzureCosmosDBConnection\": \"&lt;PRIMARY CONNECTION STRING for Cosmos DB in Azure portal&gt;\",\r\n    \"FUNCTIONS_WORKER_RUNTIME\": \"java\",\r\n    \"targeturi\": \"&lt;URI for target database\/collection from Portal&gt;\",\r\n    \"targeturikey\": \"&lt;PRIMARY KEY for target database\/collection from Portal&gt;\"\r\n  }\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<p>Watch the video below to see how to deploy to Azure! To follow along with this video, you should have the pre-requisites from the above video already installed, plus the following:<\/p>\n<ul>\n<li>Azure CLI &#8211; instructions <a href=\"https:\/\/docs.microsoft.com\/cli\/azure\/install-azure-cli?view=azure-cli-latest\">here<\/a>.<\/li>\n<li>The Cosmos DB Java SDK v2.6.5 by adding below dependency in pom.xml<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\">&lt;dependency&gt;\r\n  &lt;groupId&gt;com.microsoft.azure&lt;\/groupId&gt;\r\n  &lt;artifactId&gt;azure-cosmosdb&lt;\/artifactId&gt;\r\n  &lt;version&gt;2.6.5&lt;\/version&gt;\r\n&lt;\/dependency&gt;<\/pre>\n<p>&nbsp;<\/p>\n<p><iframe title=\"How to deploy event sourcing solution for Azure Cosmos DB with Azure Functions (Java) in 7 minutes!\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/ZbTkBUHiupA?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p>For more information about Azure Cosmos DB&#8217;s change feed and it&#8217;s use cases, go <a href=\"https:\/\/docs.microsoft.com\/en-us\/azure\/cosmos-db\/change-feed\">here<\/a>!<\/p>\n<p>For the official documentation on creating an Azure Function triggered by Cosmos DB, go <a href=\"https:\/\/docs.microsoft.com\/azure\/cosmos-db\/change-feed-functions\">here<\/a>!<\/p>\n<h2><span style=\"font-size: 14pt;\"><strong>Get started<\/strong><\/span><\/h2>\n<p>Create a new account using the Azure Portal, ARM template or Azure CLI and connect to it using your favourite tools.\u00a0Stay up-to-date on the latest Azure\u202f<a href=\"https:\/\/twitter.com\/search?q=%23cosmosdb\">#CosmosDB<\/a>\u202fnews and features by following us on Twitter\u202f<a href=\"https:\/\/twitter.com\/azurecosmosdb\">@AzureCosmosDB<\/a>. We are really excited to see what you will build with Azure Cosmos DB!<\/p>\n<h2><span style=\"font-size: 14pt;\">About Azure Cosmos DB<\/span><\/h2>\n<p><a href=\"http:\/\/www.azurecosmosdb.com\">Azure Cosmos DB<\/a> is a globally distributed, multi-model NoSQL database service that enables you to read and write data from any Azure region. It offers <a href=\"https:\/\/docs.microsoft.com\/azure\/cosmos-db\/distribute-data-globally\">turnkey global distribution<\/a>, guarantees\u00a0<a href=\"https:\/\/azure.microsoft.com\/support\/legal\/sla\/cosmos-db\/v1_3\/\">single-digit millisecond<\/a> latency at the 99<sup>th<\/sup>\u00a0percentile, 99.999 percent\u00a0<a href=\"https:\/\/docs.microsoft.com\/azure\/cosmos-db\/high-availability\">high availability<\/a>, with <a href=\"https:\/\/docs.microsoft.com\/azure\/cosmos-db\/scaling-throughput\">elastic scaling<\/a>\u00a0of\u00a0<a href=\"https:\/\/docs.microsoft.com\/azure\/cosmos-db\/request-units\">throughput and storage<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>&nbsp; Creating event sourcing solutions with Azure Cosmos DB is easy with Azure Functions Triggers, where you can leverage the Change Feed Processor&#8216;s powerful scaling and reliable event detection functionality, without the need to maintain any worker infrastructure. You can just focus on your Azure Function&#8217;s logic without worrying about the rest of the event-sourcing [&hellip;]<\/p>\n","protected":false},"author":9387,"featured_media":551,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[644,643,19],"tags":[499,536,500,538,497,537,498],"class_list":["post-595","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-change-feed","category-java-sdk","category-tips-and-tricks","tag-azure-cosmos-db","tag-azure-functions-trigger","tag-change-feed","tag-cosmos-java-azure-functions","tag-event-sourcing","tag-java","tag-visual-studio-code"],"acf":[],"blog_post_summary":"<p>&nbsp; Creating event sourcing solutions with Azure Cosmos DB is easy with Azure Functions Triggers, where you can leverage the Change Feed Processor&#8216;s powerful scaling and reliable event detection functionality, without the need to maintain any worker infrastructure. You can just focus on your Azure Function&#8217;s logic without worrying about the rest of the event-sourcing [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/posts\/595","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/users\/9387"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/comments?post=595"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/posts\/595\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/media\/551"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/media?parent=595"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/categories?post=595"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/tags?post=595"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}