Azure function java example

Azure function java example DEFAULT

In this article, we will explore how to create and publish Azure functions and integrate them with a SQL database in Java.

You Will Learn

How can we create and publish Azure functions by using Java:

  1. .
  2. .
  3. .
  4. .
  5. to integrate with Azure SQL.

Tools Required

  • Maven 3.0+ build tool.
  • Eclipse as IDE. 
  • Postman.
  • Azure Subscription.

The complete Maven project with code examples is available in Github: https://github.com/kanuparthikish/Java-AzureFunctions.git.

Add a new Arch type while creating a new Maven project in Eclipse. Please refer to the following link for the latest version: https://mvnrepository.com/artifact/com.microsoft.azure/azure-functions-archetype.

Creating a new Maven project

Selecting an Archtype

Enter the value based on the Maven Rules in the “Group Id” and “Artifact Id” fields and click “Finish”.

Entering group and artifact Ids

HTTP Trigger

Create the HTTP Trigger Function that reads a request parameter and request body as a simple Employee POJO. It then sends the response as an HTTP status OK (200) with a request parameter value and object name.

In case a request parameter value is empty or null, then it will send a response as HTTP Status Bad request (400).

Sample Code for HTTP Trigger

Sample Code for Employee pojo

Sample Code for Employee pojo

Sample Code for Employee pojo

In the POM.xml file, update the function App name as “kishazureappfunction”.

Updating POM.xml file

Update the resource group name, region, OS, and App service plan:

Updating POM.xml file

We can create a function name and other details, like subscription, resource group, OS details, and storage details in the Azure portal and update those details in the POM.xml file.

To deploy the Azure function, use the following command

If the Azure function is published successfully, we'll see the following output:

Azure function published

Log on to the Azure Web portal. Under resource group, you can find the Azure app function and ASP:

Azure Web portal

Adding ASP

Navigate to the app function:

App function

Navigate to the HTTP example:

HTTPExample

The HttpExample function listens on the api/HttpExample route, and the URL is https://kishazureappfunction.azurewebsites.net/api/HttpExample.

Listening on api/HttpExample route

Click on the log console:

Log console output

Go to Postman and add the new request with the request parameter "name" as "hello".

Adding key-values in Postman

And a request body with employee information as JSON.

Adding employee into request body

Click on send request.

Navigate to the HTTPExample logs console on the Azure portal. The request parameters and Employee Object details are printed in console:

GET request output

The HTTP Response posted with a status of 200.

HTTP response

If a request parameter value is null, then the HTTP response is posted with a status of 400.

400 status response

To the above HTTP trigger code, I have added a new input parameter so that the Employee pojo could be written to the Azure storage queue for each HTTP request received.

Updating HttpTriggerFunction

Updating HttpTriggerFunctionTo Deploy the Azure function, use the following command:

The system creates a new Azure storage account under the resource group:

Creating new Azure storage account

Navigate to the storage account -> Queues. No new queues were created, but when we send a new HTPP request to the HTTP Trigger function, a new queue is created.

Sending request to HttpTriggerFunction

New queue created

The queue contains a message text, as an Employee JSON object.

New employee object

Queue Trigger

Create the Queue Trigger Function, which polls the Employee POJO from the httpRequestQueue (Message posted in previous HttpTrigger function) and writes a log each time a queue item is processed.

QueueTriggerExample class



 

The data type attribute should be empty so that message text will be converted to an Employee pojo. To Deploy the Azure function, use the following command:

Navigate to the QueueTrigger logs console on the Azure portal:

QueueTrigger logs

Post a new request to the HTTP Trigger function:

Posting a new request

The function consumed the message from the and Employee object details printed in the logger console.

QueueTrigger console

To the above code, I have added a new input parameter, , so that it will read a blob file from Azure storage based on an employee object id value that matches with the name of the filename.

 
 

The value is Employee Object--> id property.

Create a new blob container in the storage account

Creating a new blob container

Here, we've uploaded two text files to the employee container with the employee id value:

Uploading text files to employee container

To deploy the Azure function, use the following command:

Navigate to the QueueTriger logs console on the Azure portal:

QueueTrigger logs

Send the HTTP Trigger request with a simple Employee JSON object.

Employee JSON object

The object will be based on the employee id of the name of the blob file details printed in the logger console.

QueueTrigger console output

If the employee id blob file is not found in the container, the system throws an exception and creates a poison queue message placed into the poison queue for the exception process.

System throwing exception

Error added to poison queue

Blob Trigger

The following code block creates the Blob Trigger function that logs the filename and size when a blob is added or updated in the mydrive container:

BlobTriggerFunction

Create a mydrive container in Azure storage and upload a sample file.

Creating mydrive container

To Deploy the Azure function, use the following command:

Navigate to the BlobTrigger logs console in the Azure portal:

BlobTrigger logs

To the above BlobTrigger code, I have added a new input parameter, , so that it will read a blob file from the Azure storage Blob container and make a copy of a text blob.

Making copy of text blob

To Deploy the Azure function, use the following command:

Upload sample file

Uploading the sample file

The backup container created with the backup file.

Backup container with backup file

Time Trigger

Create the Time Trigger function that runs based a CRON expression schedule. The following function executes every minute:

TimeTriggerExample

Use the following link to generate a CRON expression scheduler: https://www.freeformatter.com/cron-expression-generator-quartz.html.

Deploy the Azure function using the following command:

Navigate to the TimerTrigger logs console in the Azure portal.

TimeTrigger logs console

TimeTrigger log output

HttpTrigger Function Integration With Azure SQL

Create the SQL Server and SQL database in Azure. Add a new table to kishoresqldb. 

Creating database in Azure

Copy the connection String value from the database.

Getting connection string

 Add the connection String value as the URL.

Adding connection string URL

Add the following dependency to the POM.xml

Adding dependency to POM.xml

To deploy the Azure function, use the following command:

Send a new request to HTTP Trigger:

Sending request to HTTP Trigger

Select the query from the table after the request:

Selecting correct query

Conclusion

I hope you explore the overview of running a Java-based Maven project and publish it to Azure functions. We have developed a serverless compute service that enables you to run code on-demand.

Sours: https://dzone.com/articles/how-to-create-amp-publish-azure-functions-on-java

Azure Functions Java developer guide

This guide contains detailed information to help you succeed developing Azure Functions using Java.

As a Java developer, if you're new to Azure Functions, please consider first reading one of the following articles:

Java function basics

A Java function is a method, decorated with the annotation . This method defines the entry for a Java function, and must be unique in a particular package. The package can have multiple classes with multiple public methods annotated with . A single package is deployed to a function app in Azure. When running in Azure, the function app provides the deployment, execution, and management context for your individual Java functions.

Programming model

The concepts of triggers and bindings are fundamental to Azure Functions. Triggers start the execution of your code. Bindings give you a way to pass data to and return data from a function, without having to write custom data access code.

Create Java functions

To make it easier to create Java functions, there are Maven-based tooling and archetypes that use predefined Java templates to help you create projects with a specific function trigger.

Maven-based tooling

The following developer environments have Azure Functions tooling that lets you create Java function projects:

The article links above show you how to create your first functions using your IDE of choice.

Project Scaffolding

If you prefer command line development from the Terminal, the simplest way to scaffold Java-based function projects is to use archetypes. The Java Maven archetype for Azure Functions is published under the following groupId:artifactId: com.microsoft.azure:azure-functions-archetype.

The following command generates a new Java function project using this archetype:

To get started using this archetype, see the Java quickstart.

Folder structure

Here is the folder structure of an Azure Functions Java project:

You can use a shared host.json file to configure the function app. Each function has its own code file (.java) and binding configuration file (function.json).

You can put more than one function in a project. Avoid putting your functions into separate jars. The in the target directory is what gets deployed to your function app in Azure.

Triggers and annotations

Functions are invoked by a trigger, such as an HTTP request, a timer, or an update to data. Your function needs to process that trigger, and any other inputs, to produce one or more outputs.

Use the Java annotations included in the com.microsoft.azure.functions.annotation.* package to bind input and outputs to your methods. For more information, see the Java reference docs.

Important

You must configure an Azure Storage account in your local.settings.json to run Azure Blob storage, Azure Queue storage, or Azure Table storage triggers locally.

Example:

Here is the generated corresponding by the azure-functions-maven-plugin:

Java versions

The version of Java used when creating the function app on which functions runs in Azure is specified in the pom.xml file. The Maven archetype currently generates a pom.xml for Java 8, which you can change before publishing. The Java version in pom.xml should match the version on which you have locally developed and tested your app.

Supported versions

The following table shows current supported Java versions for each major version of the Functions runtime, by operating system:

Functions versionJava versions (Windows)Java versions (Linux)
3.x11
8
11
8
2.x8n/a

Unless you specify a Java version for your deployment, the Maven archetype defaults to Java 8 during deployment to Azure.

Specify the deployment version

You can control the version of Java targeted by the Maven archetype by using the parameter. The value of this parameter can be either or .

The Maven archetype generates a pom.xml that targets the specified Java version. The following elements in pom.xml indicate the Java version to use:

ElementJava 8 valueJava 11 valueDescription
1.811Version of Java used by the maven-compiler-plugin.
811Java version hosted by the function app in Azure.

The following examples show the settings for Java 8 in the relevant sections of the pom.xml file:

Important

You must have the JAVA_HOME environment variable set correctly to the JDK directory that is used during code compiling using Maven. Make sure that the version of the JDK is at least as high as the setting.

Specify the deployment OS

Maven also lets you specify the operating system on which your function app runs in Azure. Use the element to choose the operating system.

ElementWindowsLinuxDocker

The following example shows the operating system setting in the section of the pom.xml file:

JDK runtime availability and support

For local development of Java function apps, download and use the appropriate Azul Zulu Enterprise for Azure Java JDKs from Azul Systems. Azure Functions uses an Azul Java JDK runtime when you deploy your function app to the cloud.

Azure support for issues with the JDKs and function apps is available with a qualified support plan.

Customize JVM

Functions lets you customize the Java virtual machine (JVM) used to run your Java functions. The following JVM options are used by default:

    You can provide additional arguments in an app setting named . You can add app settings to your function app deployed to Azure in the Azure portal or the Azure CLI.

    Important

    In the Consumption plan, you must also add the WEBSITE_USE_PLACEHOLDER setting with a value of 0 for the customization to work. This setting does increase the cold start times for Java functions.

    Azure portal

    In the Azure portal, use the Application Settings tab to add the setting.

    Azure CLI

    You can use the az functionapp config appsettings set command to set , as in the following example:

    This example enables headless mode. Replace with the name of your function app, and with the resource group.

    Third-party libraries

    Azure Functions supports the use of third-party libraries. By default, all dependencies specified in your project file are automatically bundled during the goal. For libraries not specified as dependencies in the file, place them in a directory in the function's root directory. Dependencies placed in the directory are added to the system class loader at runtime.

    The dependency is provided on the classpath by default, and doesn't need to be included in the directory. Also, azure-functions-java-worker adds dependencies listed here to the classpath.

    Data type support

    You can use Plain old Java objects (POJOs), types defined in , or primitive data types such as String and Integer to bind to input or output bindings.

    POJOs

    For converting input data to POJO, azure-functions-java-worker uses the gson library. POJO types used as inputs to functions should be .

    Binary data

    Bind binary inputs or outputs to , by setting the field in your function.json to :

    If you expect null values, use .

    Bindings

    Input and output bindings provide a declarative way to connect to data from within your code. A function can have multiple input and output bindings.

    Input binding example

    You invoke this function with an HTTP request.

    • HTTP request payload is passed as a for the argument .
    • One entry is retrieved from Table storage, and is passed as to the argument .

    To receive a batch of inputs, you can bind to , , , or .

    This function gets triggered whenever there is new data in the configured event hub. Because the is set to , the function receives a batch of messages from the event hub. from event hub gets converted to for the function execution.

    Output binding example

    You can bind an output binding to the return value by using .

    If there are multiple output bindings, use the return value for only one of them.

    To send multiple output values, use defined in the package.

    You invoke this function on an HttpRequest. It writes multiple values to Queue storage.

    HttpRequestMessage and HttpResponseMessage

    These are defined in . They are helper types to work with HttpTrigger functions.

    Specialized typeTargetTypical usage
    HTTP TriggerGets method, headers, or queries
    HTTP Output BindingReturns status other than 200

    Metadata

    Few triggers send trigger metadata along with input data. You can use annotation to bind to trigger metadata.

    In the preceding example, the is bound to the query string parameter in the HTTP request URL, . Here's another example, showing how to bind to from queue trigger metadata.

    Note

    The name provided in the annotation needs to match the metadata property.

    Execution context

    , defined in the , contains helper methods to communicate with the functions runtime. For more information, see the ExecutionContext reference article.

    Logger

    Use , defined in , to write logs from function code.

    Example:

    View logs and trace

    You can use the Azure CLI to stream Java stdout and stderr logging, as well as other application logging.

    Here's how to configure your function app to write application logging by using the Azure CLI:

    To stream logging output for your function app by using the Azure CLI, open a new command prompt, Bash, or Terminal session, and enter the following command:

    The az webapp log tail command has options to filter output by using the option.

    To download the log files as a single ZIP file by using the Azure CLI, open a new command prompt, Bash, or Terminal session, and enter the following command:

    You must have enabled file system logging in the Azure portal or the Azure CLI before running this command.

    Environment variables

    In Functions, app settings, such as service connection strings, are exposed as environment variables during execution. You can access these settings by using, .

    The following example gets the application setting, with the key named :

    Note

    The value of AppSetting FUNCTIONS_EXTENSION_VERSION should be ~2 or ~3 for an optimized cold start experience.

    Next steps

    For more information about Azure Functions Java development, see the following resources:

    Sours: https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-java
    1. Heritage bank nw
    2. Freehold gmc dealer
    3. Jack hartmann
    4. Bobcat hydrostatic fluid

    Quickstart: Create a Java function in Azure from the command line

    In this article, you use command-line tools to create a Java function that responds to HTTP requests. After testing the code locally, you deploy it to the serverless environment of Azure Functions.

    If Maven isn't your preferred development tool, check out our similar tutorials for Java developers:

    Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.

    Configure your local environment

    Before you begin, you must have the following:

    Prerequisite check

    • In a terminal or command window, run to check that the Azure Functions Core Tools are version 3.x.

    • Run to check that the Azure CLI version is 2.4 or later.

    • Run to sign in to Azure and verify an active subscription.

    Create a local function project

    In Azure Functions, a function project is a container for one or more individual functions that each responds to a specific trigger. All functions in a project share the same local and hosting configurations. In this section, you create a function project that contains a single function.

    1. In an empty folder, run the following command to generate the Functions project from a Maven archetype.

      Important

      • Use if you want your functions to run on Java 11. To learn more, see Java versions.
      • The environment variable must be set to the install location of the correct version of the JDK to complete this article.
    2. Maven asks you for values needed to finish generating the project on deployment.
      Provide the following values when prompted:

      PromptValueDescription
      groupIdA value that uniquely identifies your project across all projects, following the package naming rules for Java.
      artifactIdA value that is the name of the jar, without a version number.
      versionChoose the default value.
      packageA value that is the Java package for the generated function code. Use the default.
    3. Type or press Enter to confirm.

      Maven creates the project files in a new folder with a name of artifactId, which in this example is .

    4. Navigate into the project folder:

      This folder contains various files for the project, including configurations files named local.settings.json and host.json. Because local.settings.json can contain secrets downloaded from Azure, the file is excluded from source control by default in the .gitignore file.

    (Optional) Examine the file contents

    If desired, you can skip to Run the function locally and examine the file contents later.

    Function.java

    Function.java contains a method that receives request data in the variable is an HttpRequestMessage that's decorated with the HttpTrigger annotation, which defines the trigger behavior.

    The response message is generated by the HttpResponseMessage.Builder API.

    pom.xml

    Settings for the Azure resources created to host your app are defined in the configuration element of the plugin with a groupId of in the generated pom.xml file. For example, the configuration element below instructs a Maven-based deployment to create a function app in the resource group in the region. The function app itself runs on Windows hosted in the plan, which by default is a serverless Consumption plan.

    You can change these settings to control how resources are created in Azure, such as by changing from to before initial deployment. For a complete list of settings supported by the Maven plug-in, see the configuration details.

    FunctionTest.java

    The archetype also generates a unit test for your function. When you change your function to add bindings or add new functions to the project, you'll also need to modify the tests in the FunctionTest.java file.

    Run the function locally

    1. Run your function by starting the local Azure Functions runtime host from the LocalFunctionProj folder:

      Toward the end of the output, the following lines should appear:

      ... Now listening on: http://0.0.0.0:7071 Application started. Press Ctrl+C to shut down. Http Functions: HttpExample: [GET,POST] http://localhost:7071/api/HttpExample ...

      Note

      If HttpExample doesn't appear as shown above, you likely started the host from outside the root folder of the project. In that case, use Ctrl+C to stop the host, navigate to the project's root folder, and run the previous command again.

    2. Copy the URL of your function from this output to a browser and append the query string , making the full URL like . The browser should display a message that echoes back your query string value. The terminal in which you started your project also shows log output as you make requests.

    3. When you're done, use Ctrl+C and choose to stop the functions host.

    Deploy the function project to Azure

    A function app and related resources are created in Azure when you first deploy your functions project. Settings for the Azure resources created to host your app are defined in the pom.xml file. In this article, you'll accept the defaults.

    Tip

    To create a function app running on Linux instead of Windows, change the element in the pom.xml file from to . Running Linux in a consumption plan is supported in these regions. You can't have apps that run on Linux and apps that run on Windows in the same resource group.

    1. Before you can deploy, sign in to your Azure subscription using either Azure CLI or Azure PowerShell.

      The az login command signs you into your Azure account.

      The Connect-AzAccount cmdlet signs you into your Azure account.

    2. Use the following command to deploy your project to a new function app.

      This creates the following resources in Azure:

      • Resource group. Named as java-functions-group.
      • Storage account. Required by Functions. The name is generated randomly based on Storage account name requirements.
      • Hosting plan. Serverless hosting for your function app in the westus region. The name is java-functions-app-service-plan.
      • Function app. A function app is the deployment and execution unit for your functions. The name is randomly generated based on your artifactId, appended with a randomly generated number.

      The deployment packages the project files and deploys them to the new function app using zip deployment. The code runs from the deployment package in Azure.

    Invoke the function on Azure

    Because your function uses an HTTP trigger, you invoke it by making an HTTP request to its URL in the browser or with a tool like curl.

    Copy the complete Invoke URL shown in the output of the publish command into a browser address bar, appending the query parameter . The browser should display similar output as when you ran the function locally.

    The output of the function run on Azure in a browser

    Run with the Invoke URL, appending the parameter . The output of the command should be the text, "Hello Functions."

    The output of the function run on Azure using curl

    Run the following command to view near real-time streaming logs:

    In a separate terminal window or in the browser, call the remote function again. A verbose log of the function execution in Azure is shown in the terminal.

    Clean up resources

    If you continue to the next step and add an Azure Storage queue output binding, keep all your resources in place as you'll build on what you've already done.

    Otherwise, use the following command to delete the resource group and all its contained resources to avoid incurring further costs.

    Next steps

    Sours: https://docs.microsoft.com/en-us/azure/azure-functions/create-first-function-cli-java
    How to setup a HttpTrigger using Azure Functions in Java (2021). Your first step to micro-services.

    Java in Azure functions

    Azure Functions is the serverless computing in Azure architecture that provides a programming model for event-driven applications

    Back in February, Microsoft announced Java support in Azure Functions 2.0. This is good news to Java developers accessing Azure as a cloud-based provider and leveraging Azure Functions as computing components.

    You may also like: Azure for Java Developers

    In this article, we will study an example of developing and executing a Java-based application running in Azure Functions.

    Create Function App From Azure Portal

    Microsoft Function App

    First, you need to provide the function name and other details like subscription, resource group, and OS details to provision Azure Functions

    Function App

    Hosting Plan

    Select the hosting plan. Azure Functions runs on two plans:

    • Consumption Plan: In this plan, instances of Azure Functions host are dynamically added or removed based on the number of incoming events. Billing is based on the number of executions, memory used, and execution time. Maximum memory in this plan is 1.5 GB per instance

    • App Service Plan: In this plan, Azure Functions runs on dedicated VM's as other App Service Apps. Memory in this plan goes from 1.75 GB to 14 GB per instance

    There is one more plan: "Premium," which is in the preview stage. Choose any of the above plans, depending on the business requirements and usage.

    Then, choose a runtime stack for the execution environment. In this requirement, we select Java:

    Select Java for execution environment

    Select Storage Account and Application Insights as logging of Azure Functions is directly integrated with Application Insights:

    Select Application Insights

    With the above details, the Function App is provisioned in the given usage plan. With this simple example, we can see how we can implement a Java service published and hosted in Azure Functions.

    Create a Maven project in your local system with the Maven archetype for an Azure Functions environment.

    Below is the command to create a Maven project:

    Import the Maven project in your favorite IDE, like Eclipse or Visual Studio Code. Then, open the generated pom.xml and update the following details:

    These details are obtained when you have provisioned Azure Functions from the portal.

    Also, add any other third-party libraries as dependencies in the Maven project required for your Java application

    In our example, we create a simple Java service with two methods — one serving  HTTP GET requests and another serving HTTP POST requests.

    The code below is for a POST request that creates order. In our example, we are creating a dummy order and there is no interaction with any back-end system. The purpose of this example is to show how we can build a POST request in Java published to the Azure Function environment:

    The above function is annotated with , which is  and takes the object of  and  object as parameters.

    The request body passed in POST request can be obtained using  method of  object.

     has methods that get function-related configurations like invocation id, function name, and logger object that logs messages to Application Insights.

    Similarly, an example for a GET request service is shown below and provides order details by passing order Id as a query parameter in the URL:

    The above function is annotated with the function name . This function is accessed by GET request with "" parameter passed as a query parameter in the URL

    The query parameter passed in the URL can be obtained by  method of .

    The required classes for Java code to run in Azure Functions are from the Java package "com.microsoft.azure.functions."

    The host.json file is also generated in the Maven project; then you can add the below entry:

    When you enable bundles, a predefined set of extension packages is automatically installed.

    Now, run the Maven project locally:

    When functions run as locally (first-time setup), we get this exception:

    Caused by: java.lang.Exception: Azure Functions Core Tools not found. Please go to https://aka.ms/azfunc-install to install Azure Functions Core Tools first. at

    Solution: Install Azure Function-core tools using npm (Node Package Manager) with the following command:

    Test the function in the local environment, and once everything is fine, then start publishing to Azure.

    To start publishing to Azure, log into the Azure portal using the below command:

    Once login is a success, publish and deploy the Java project to Azure Functions:

    Once the project is deployed, two functions can be visualized in the portal from the Azure Function resource:

    portal from the Azure Function resource

    The functions  and , where we have annotated with the function name in the Java code for POST service and GET service, are being seen as separate individual functions with the same name as the one annotated.

    To get the URL for , click on the  function and get the URL by clicking the Get function URL

    function.json

    Get function URL

    The format is as below:

    https://mybrandorderservice.azurewebsites.net/api/createorder?code=<code>

    is the function app name we provided during provisioning of Azure Functions,  is the function name we provided in the Java method, and code query parameter is the security code generated at the Azure Functions level.

    Similarly, for the GET request in our example, the URL format is shown below:

    https://mybrandorderservice.azurewebsites.net/api/listorder?orderId=8976&code=<codeid>

     is the query parameter we defined for passing custom value (in this example, the  value).

    The URL pattern starts with  for the function and gets published and hosted as Azure Functions.

    If we can test our example POST service from the REST client:

    testing our example POST service

    We get the following response from the  service:

    Response from createorder service

    To view the logs, navigate to the Monitor section of the particular function in the Azure portal and see the logs for the  function

    Image title

    Click on the following log generated:

    generated log

    The detailed log will be presented from the Application Insights. We can see the info log from the Java code that got logged for the  function, as shown below.

    In this way, we can monitor any errors, debug, and collect info traces from the Java project.

    Monitoring and debugging info traces from the Java project.

    Conclusion

    We hope you enjoyed this overview of running a Java-based Maven project and publishing it to Azure Functions. We have seen how we can develop services for POST and GET request methods in Java, and then host it in Azure Functions with monitoring enabled by tracing the logger details from the Application Insights.

    Further Reading

    Getting Started With Azure Functions

    Azure for Java Developers

    When to Use Logic Apps and Azure Functions

    Sours: https://dzone.com/articles/azure-functions-in-java

    Java azure example function

    Azure Functions example in Java

    page_typelanguagesproductsdescriptionurlFragment

    sample

    This repository contains sample for Azure Functions in Java

    azure-functions-java

    This sample show a basis usage for how to use http-trigger for Azure Functions in Java.

    Contents

    Outline the file contents of the repository. It helps users navigate the codebase, build configuration and any related assets.

    File/folderDescription
    Sample source code.
    Define what to ignore at commit time.
    The gradle configuration to this sample.
    The maven configuration to this sample.
    List of changes to the sample.
    Guidelines for contributing to the sample.
    This README file.
    The license for the sample.

    Prerequisites

    • Gradle 4.10+
    • Latest Function Core Tools
    • Azure CLI. This plugin use Azure CLI for authentication, please make sure you have Azure CLI installed and logged in.

    Setup

    az login az account set -s <your subscription id>

    Running the sample

    ./mvnw clean package azure-functions:run
    ./gradlew clean azureFunctionsRun

    Deploy the sample on Azure

    ./mvnw clean package azure-functions:deploy
    ./gradlew clean azureFunctionsDeploy

    NOTE: please replace '/' with '\' when you are running on windows.

    Contributing

    This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

    When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

    This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

    Telemetry

    This project collects usage data and sends it to Microsoft to help improve our products and services. Read Microsoft's privacy statement to learn more. If you would like to opt out of sending telemetry data to Microsoft, you can set to false in the plugin configuration. Please read our document to find more details about allowTelemetry.

    Sours: https://github.com/Azure-Samples/azure-functions-samples-java
    HTTP Triggered Azure Functions

    Quickstart: Create a Java function in Azure using Visual Studio Code

    • 7 minutes to read

    In this article, you use Visual Studio Code to create a Java function that responds to HTTP requests. After testing the code locally, you deploy it to the serverless environment of Azure Functions.

    If Visual Studio Code isn't your preferred development tool, check out our similar tutorials for Java developers:

    Completing this quickstart incurs a small cost of a few USD cents or less in your Azure account.

    Configure your environment

    Before you get started, make sure you have the following requirements in place:

    Create your local project

    In this section, you use Visual Studio Code to create a local Azure Functions project in Java. Later in this article, you'll publish your function code to Azure.

    1. Choose the Azure icon in the Activity bar, then in the Azure: Functions area, select the Create new project... icon.

      Choose Create a new project

    2. Choose a directory location for your project workspace and choose Select.

      Note

      These steps were designed to be completed outside of a workspace. In this case, do not select a project folder that is part of a workspace.

    3. Provide the following information at the prompts:

      • Select a language for your function project: Choose .

      • Select a version of Java: Choose or , the Java version on which your functions run in Azure. Choose a Java version that you've verified locally.

      • Provide a group ID: Choose .

      • Provide an artifact ID: Choose .

      • Provide a version: Choose .

      • Provide a package name: Choose .

      • Provide an app name: Choose .

      • Authorization level: Choose , which enables anyone to call your function endpoint. To learn about authorization level, see Authorization keys.

      • Select how you would like to open your project: Choose .

    4. Using this information, Visual Studio Code generates an Azure Functions project with an HTTP trigger. You can view the local project files in the Explorer. To learn more about files that are created, see Generated project files.

    Run the function locally

    Visual Studio Code integrates with Azure Functions Core tools to let you run this project on your local development computer before you publish to Azure.

    1. To call your function, press to start the function app project. Output from Core Tools is displayed in the Terminal panel. Your app starts in the Terminal panel. You can see the URL endpoint of your HTTP-triggered function running locally.

      Local function VS Code output

      If you have trouble running on Windows, make sure that the default terminal for Visual Studio Code isn't set to WSL Bash.

    2. With Core Tools running, go to the Azure: Functions area. Under Functions, expand Local Project > Functions. Right-click (Windows) or click (macOS) the function and choose Execute Function Now....

      Execute function now from Visual Studio Code

    3. In Enter request body you see the request message body value of . Press Enter to send this request message to your function.

    4. When the function executes locally and returns a response, a notification is raised in Visual Studio Code. Information about the function execution is shown in Terminal panel.

    5. Press to stop Core Tools and disconnect the debugger.

    After you've verified that the function runs correctly on your local computer, it's time to use Visual Studio Code to publish the project directly to Azure.

    Sign in to Azure

    Before you can publish your app, you must sign in to Azure.

    1. If you aren't already signed in, choose the Azure icon in the Activity bar, then in the Azure: Functions area, choose Sign in to Azure.... If you don't already have one, you can Create a free Azure account. Students can create a free Azure account for Students.

      Sign in to Azure within VS Code

      If you're already signed in, go to the next section.

    2. When prompted in the browser, choose your Azure account and sign in using your Azure account credentials.

    3. After you've successfully signed in, you can close the new browser window. The subscriptions that belong to your Azure account are displayed in the Side bar.

    Publish the project to Azure

    In this section, you create a function app and related resources in your Azure subscription and then deploy your code.

    Important

    Publishing to an existing function app overwrites the content of that app in Azure.

    1. Choose the Azure icon in the Activity bar, then in the Azure: Functions area, choose the Deploy to function app... button.

      Publish your project to Azure

    2. Provide the following information at the prompts:

      • Select folder: Choose a folder from your workspace or browse to one that contains your function app. You won't see this if you already have a valid function app opened.

      • Select subscription: Choose the subscription to use. You won't see this if you only have one subscription.

      • Select Function App in Azure: Choose . (Don't choose the option, which isn't covered in this article.)

      • Enter a globally unique name for the function app: Type a name that is valid in a URL path. The name you type is validated to make sure that it's unique in Azure Functions.

      • Select a location for new resources: For better performance, choose a region near you.

      The extension shows the status of individual resources as they are being created in Azure in the notification area.

      Notification of Azure resource creation

    3. When completed, the following Azure resources are created in your subscription, using names based on your function app name:

      • A resource group, which is a logical container for related resources.
      • A standard Azure Storage account, which maintains state and other information about your projects.
      • A consumption plan, which defines the underlying host for your serverless function app.
      • A function app, which provides the environment for executing your function code. A function app lets you group functions as a logical unit for easier management, deployment, and sharing of resources within the same hosting plan.
      • An Application Insights instance connected to the function app, which tracks usage of your serverless function.

      A notification is displayed after your function app is created and the deployment package is applied.

      Tip

      By default, the Azure resources required by your function app are created based on the function app name you provide. By default, they are also created in the same new resource group with the function app. If you want to either customize the names of these resources or reuse existing resources, you need to instead publish the project with advanced create options.

    4. Select View Output in this notification to view the creation and deployment results, including the Azure resources that you created. If you miss the notification, select the bell icon in the lower right corner to see it again.

      Create complete notification

    Run the function in Azure

    1. Back in the Azure: Functions area in the side bar, expand your subscription, your new function app, and Functions. Right-click (Windows) or click (macOS) the function and choose Execute Function Now....

      Execute function now in Azure from Visual Studio Code

    2. In Enter request body you see the request message body value of . Press Enter to send this request message to your function.

    3. When the function executes in Azure and returns a response, a notification is raised in Visual Studio Code.

    Clean up resources

    When you continue to the next step and add an Azure Storage queue binding to your function, you'll need to keep all your resources in place to build on what you've already done.

    Otherwise, you can use the following steps to delete the function app and its related resources to avoid incurring any further costs.

    1. In Visual Studio Code, press to open the command palette. In the command palette, search for and select .

    2. Choose your function app, and press . The function app page opens in the Azure portal.

    3. In the Overview tab, select the named link next to Resource group.

      Select the resource group to delete from the function app page.

    4. In the Resource group page, review the list of included resources, and verify that they are the ones you want to delete.

    5. Select Delete resource group, and follow the instructions.

      Deletion may take a couple of minutes. When it's done, a notification appears for a few seconds. You can also select the bell icon at the top of the page to view the notification.

    To learn more about Functions costs, see Estimating Consumption plan costs.

    Next steps

    You have used Visual Studio Code to create a function app with a simple HTTP-triggered function. In the next article, you expand that function by connecting to Azure Storage. To learn more about connecting to other Azure services, see Add bindings to an existing function in Azure Functions.

    Feedback

    View all page feedback

    Sours: https://docs.microsoft.com/en-us/azure/azure-functions/create-first-function-vs-code-java

    You will also like:

    Drunk a couple of glasses of local wine, and finally, having undressed, I realized that the people were adequate, no one bothered to my wife, and I relaxed. More precisely, I sometimes relaxed, then again tensed when I saw that my wife was not uninteresting to our new acquaintances.

    That they are happy to jump around her with their reproductive organs, trying to attract her attention to themselves.



    1729 1730 1731 1732 1733