请使用 spring-cloud-function 5.0.1 获取最新稳定版本!spring-doc.cadn.net.cn

Microsoft Azure Functions

Azure function adapter for deploying Spring Cloud Function applications as native Azure Java Functions.spring-doc.cadn.net.cn

该代码 0 处的编程模型通过 Java 注释来定义处理程序方法以及它们的输入和输出类型,广泛依赖于这些注释。在编译时,由提供的 Azure Maven/Gradle 插件处理已注释的类,生成所需的 Azure 函数绑定文件、配置和软件包资产。注释只是将你的 Java 函数注册为 Azure 函数的一种类型安全的方法。spring-doc.cadn.net.cn

Spring Cloud Function 适配器-azure 扩展了基本编程模型,提供了对 Spring 和 Spring Cloud Function 的支持。使用该适配器,您可以使用依赖注入来构建您的 Spring Cloud Function 应用程序,然后自动将必要的服务注入到 Azure 处理程序方法中。spring-doc.cadn.net.cn

scf azure adapter
For Web-based function applications, you can replace the generic adapter-azure with the specialized spring-cloud-function-adapter-azure-web. With the Azure Web Adapter you can deploy any Spring Web application as an Azure, HttpTrigger, function. This adapter hides the Azure annotations complexity and uses the familiar Spring Web programming model instead. For further information follow the Azure Web Adapter section below.

Azure 适配器

为 Azure Functions 提供 SpringSpring Cloud Function 的集成。spring-doc.cadn.net.cn

依赖项

在添加 Azure 函数集成之前,需要向 pom.xmlbuild.gradle 文件中添加 azure 适配器依赖项:spring-doc.cadn.net.cn

<dependencies>
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-function-adapter-azure</artifactId>
	</dependency>
</dependencies>
dependencies {
    implementation 'org.springframework.cloud:spring-cloud-function-adapter-azure'
}
version 4.0.0+ is required. Having the adapter on the classpath activates the Azure Java Worker integration.

开发指南

使用 @Component(或 @Service)注释将任何现有 Azure 函数类(例如带有 @FunctionName 处理程序)转换为 Spring 组件。 然后可以自动装配所需的依赖项(或用于 Spring Cloud Function 组合的函数目录),并在 Azure 函数处理程序中使用这些依赖项。spring-doc.cadn.net.cn

@Component (1)
public class MyAzureFunction {

	// Plain Spring bean - not a Spring Cloud Functions!
	@Autowired private Function<String, String> uppercase; (2)

	// The FunctionCatalog leverages the Spring Cloud Function framework.
	@Autowired private FunctionCatalog functionCatalog; (2)

	@FunctionName("spring") (3)
	public String plainBean( (4)
			@HttpTrigger(name = "req",
				methods = { HttpMethod.POST },
				authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
				ExecutionContext context) {

		return this.uppercase.apply(request.getBody().get());
	}

	@FunctionName("scf") (3)
	public String springCloudFunction( (5)
			@HttpTrigger(name = "req",
			methods = { HttpMethod.POST },
			authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
			ExecutionContext context) {

		// Use SCF composition. Composed functions are not just spring beans but SCF such.
		Function composed = this.functionCatalog.lookup("reverse|uppercase"); (6)

		return (String) composed.apply(request.getBody().get());
	}
}
1 指示该MyAzureFunction类是Spring框架要作为自动检测和classpath扫描候选者的“组件”。
2 自动装配定义在下面的uppercasefunctionCatalog bean。
3 @FunctionName 注释标识指定的 Azure 函数处理程序。

spring-doc.cadn.net.cn

当由触发器(例如 @HttpTrigger)调用时,函数将处理该触发器以及任何其他输入,以产生一个或多个输出。 spring-doc.cadn.net.cn

4 The plainBean method handler 是映射到一个使用自动装配的 uppercase Spring bean 来计算结果的 Azure 函数。 它展示了如何在你的 Azure 处理器中使用“纯”Spring 组件。
5 springCloudFunction 方法处理程序映射到另一个 Azure 函数,该函数使用自动装配的 FunctionCatalog 实例来计算结果。
6 展示了如何利用Spring Cloud Function 函数目录组合API。
使用 Microsoft Azure Functions 中包含在 com.microsoft.azure.functions.annotation.* 软件包中的 Java 注释,可以将输入和输出绑定到你的方法。

Azure 处理程序内部使用的业务逻辑实现看起来像一个常见的 Spring 应用程序:spring-doc.cadn.net.cn

@SpringBootApplication (1)
public class HttpTriggerDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(HttpTriggerDemoApplication.class, args);
	}

	@Bean
	public Function<String, String> uppercase() { (2)
		return payload -> payload.toUpperCase();
	}

	@Bean
	public Function<String, String> reverse() { (2)
		return payload -> new StringBuilder(payload).reverse().toString();
	}
}
1 注释为@SpringBootApplication的类在主类配置中如Main-Class所述用作#star-class-configuration
2 Spring 框架在 Azure 函数处理程序中自动注入并使用。

功能目录

注意:此处内容为自动翻译,可能有不准确之处。
Spring Cloud Function 支持用户定义函数的各种类型签名,并提供一致的执行模型。
为此,它使用函数目录将所有用户定义的函数转换为标准表示形式。
spring-doc.cadn.net.cn

Azure 连接器可以自动连接任何 Spring 组件,例如上文中的 uppercase。但这些被视为普通的 Java 类实例,而不是 Canonical Spring Cloud Functions!spring-doc.cadn.net.cn

要利用Spring Cloud Function并获得对标准函数表示形式的访问权限,您需要自动连接<0>并将其用在您的处理程序中,就像上面的<1>实例<2>处理程序一样。spring-doc.cadn.net.cn

访问 Azure ExecutionContext

有时需要以 com.microsoft.azure.functions.ExecutionContext 的形式访问 Azure 运行时提供的目标执行上下文。例如,其中一个需求是在 Azure 控制台中进行日志记录。spring-doc.cadn.net.cn

为此目的,AzureFunctionUtil.enhanceInputIfNecessary 允许您添加一个 ExecutionContext 作为消息头,您可以使用 executionContext 键检索它。spring-doc.cadn.net.cn

@FunctionName("myfunction")
public String execute(
	@HttpTrigger(name = "req",
		methods = { HttpMethod.POST },
		authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
		ExecutionContext context) {

	Message message =
		(Message) AzureFunctionUtil.enhanceInputIfNecessary(request.getBody().get(), context); (1)

	return this.uppercase.apply(message);
}
1 利用工具类AzureFunctionUtil,使用键AzureFunctionUtil.EXECUTION_CONTEXT将消息头内联为context

现在您可以从消息头中检索 ExecutionContext:spring-doc.cadn.net.cn

@Bean
public Function<Message<String>, String> uppercase(JsonMapper mapper) {
	return message -> {
		String value = message.getPayload();
		ExecutionContext context =
			(ExecutionContext) message.getHeaders().get(AzureFunctionUtil.EXECUTION_CONTEXT); (1)
		. . .
	}
}
1 检索从标头中获取ExecutionContext实例。

配置

要将你的函数应用程序在微软Azure上运行,你必须提供必要的配置,比如function.jsonhost.json,并遵守强制性的打包格式spring-doc.cadn.net.cn

通常,Azure Maven(或Gradle)插件用于从注释类生成所需的配置,并生成所需的软件包格式。spring-doc.cadn.net.cn

The Azure packaging format is not compatible with the default Spring Boot packaging (e.g. uber jar). The Disable Spring Boot Plugin section below explains how to handle this.

Azure Maven/Gradle 插件

Azure 提供 MavenGradle 插件,用于处理注释类,生成所需的配置并产生预期的软件包布局。 插件用于设置平台、运行时和 app-setting 属性,例如:spring-doc.cadn.net.cn

<plugin>
	<groupId>com.microsoft.azure</groupId>
	<artifactId>azure-functions-maven-plugin</artifactId>
	<version>1.22.0 or higher</version>

	<configuration>
		<appName>YOUR-AZURE-FUNCTION-APP-NAME</appName>
		<resourceGroup>YOUR-AZURE-FUNCTION-RESOURCE-GROUP</resourceGroup>
		<region>YOUR-AZURE-FUNCTION-APP-REGION</region>
		<appServicePlanName>YOUR-AZURE-FUNCTION-APP-SERVICE-PLANE-NAME</appServicePlanName>
		<pricingTier>YOUR-AZURE-FUNCTION-PRICING-TIER</pricingTier>

		<hostJson>${project.basedir}/src/main/resources/host.json</hostJson>

		<runtime>
			<os>linux</os>
			<javaVersion>11</javaVersion>
		</runtime>

		<appSettings>
			<property>
				<name>FUNCTIONS_EXTENSION_VERSION</name>
				<value>~4</value>
			</property>
		</appSettings>
	</configuration>
	<executions>
		<execution>
			<id>package-functions</id>
			<goals>
				<goal>package</goal>
			</goals>
		</execution>
	</executions>
</plugin>
plugins {
    id "com.microsoft.azure.azurefunctions" version "1.11.0"
	// ...
}

apply plugin: "com.microsoft.azure.azurefunctions"

azurefunctions {
	appName = 'YOUR-AZURE-FUNCTION-APP-NAME'
    resourceGroup = 'YOUR-AZURE-FUNCTION-RESOURCE-GROUP'
    region = 'YOUR-AZURE-FUNCTION-APP-REGION'
    appServicePlanName = 'YOUR-AZURE-FUNCTION-APP-SERVICE-PLANE-NAME'
    pricingTier = 'YOUR-AZURE-FUNCTION-APP-SERVICE-PLANE-NAME'

    runtime {
      os = 'linux'
      javaVersion = '11'
    }

    auth {
      type = 'azure_cli'
    }

    appSettings {
      FUNCTIONS_EXTENSION_VERSION = '~4'
    }
	// Uncomment to enable local debug
    // localDebug = "transport=dt_socket,server=y,suspend=n,address=5005"
}

有关运行时配置的更多详细信息: Java 版本, 部署 OS。spring-doc.cadn.net.cn

禁用 Spring Boot 插件

Azure Functions 预期在 Azure 执行运行时内部运行,而不是在 Spring Boot 运行时内部! 另外,Azure 需要由 Azure Maven/Gradle 插件生成的特定打包格式,该格式与默认 Spring Boot 打包不兼容。spring-doc.cadn.net.cn

您必须禁用 SpringBoot Maven/Gradle 插件或使用如本 Maven 代码段中所示的 Spring Boot 薄启动程序。spring-doc.cadn.net.cn

<plugin>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-maven-plugin</artifactId>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot.experimental</groupId>
			<artifactId>spring-boot-thin-layout</artifactId>
		</dependency>
	</dependencies>
</plugin>

主类配置

指定Main-Class/Start-Class指向你的Spring应用程序入口点,例如上例中的HttpTriggerDemoApplication类。spring-doc.cadn.net.cn

You can use the Maven start-class property or set the Main-Class attribute of your MANIFEST/META-INFO:spring-doc.cadn.net.cn

<properties>
	<start-class>YOUR APP MAIN CLASS</start-class>
	...
</properties>
jar {
    manifest {
        attributes(
            "Main-Class": "YOUR-APP-MAIN-CLASS"
        )
    }
}
另一种方法是使用环境变量MAIN_CLASS来显式设置类名。 对于本地运行,将MAIN_CLASS变量添加到你的local.settings.json文件中; 对于 Azure 门户部署,请在应用设置中设置该变量。
如果未设置MAIN_CLASS变量,Azure适配器从类路径上找到的jar中查找MANIFEST/META-INFO属性,并选择带有@SpringBootApplication@SpringBootConfiguration注释的第一个Main-Class:

元数据配置

你可以使用一个共享的 host.json 文件来配置函数应用。spring-doc.cadn.net.cn

{
	"version": "2.0",
	"extensionBundle": {
		"id": "Microsoft.Azure.Functions.ExtensionBundle",
		"version": "[4.*, 5.0.0)"
	}
}

主机.json 元数据文件包含影响函数应用实例中所有功能的功能配置选项。spring-doc.cadn.net.cn

如果文件不在项目根文件夹下,需要相应配置插件(如 hostJson Maven 属性)。

Azure Web 适配器

对于纯 Web 基础功能的应用程序,您可以将通用的adapter-azure替换为专门的spring-cloud-function-adapter-azure-web。Azure Web Adapter 可以将任何 Spring Web 应用程序部署为本机 Azure 函数,内部使用 HttpTrigger。它隐藏了 Azure 注解的复杂性,并依赖于熟悉的Spring Web编程模型。spring-doc.cadn.net.cn

要启用 Azure Web Adapter,请将适配器依赖项添加到您的 pom.xmlbuild.gradle 文件中:spring-doc.cadn.net.cn

<dependencies>
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-function-adapter-azure-web</artifactId>
	</dependency>
</dependencies>
dependencies {
    implementation 'org.springframework.cloud:spring-cloud-function-adapter-azure-web'
}

相同的配置使用说明也适用于Azure Web Adapterspring-doc.cadn.net.cn

Azure 示例

有关更多信息,请浏览以下 Azure Web Adapter 示例:spring-doc.cadn.net.cn

用法

构建和部署Azure Adapter类型和Azure Web Adapter类型的两种应用程序的通用说明。spring-doc.cadn.net.cn

构建

./mvnw -U clean package
./gradlew azureFunctionsPackage

本地运行

要在本地运行并部署到您的实时 Azure 环境中,您需要安装 Azure Functions 和 Azure CLI(参见 这里)。对于某些配置,您还需要 Azurite 模拟器spring-doc.cadn.net.cn

然后运行示例:spring-doc.cadn.net.cn

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

在 Azure 上运行

确保您已登录到 Azure 帐户。spring-doc.cadn.net.cn

az login
./mvnw azure-functions:deploy
./gradlew azureFunctionsDeploy

本地调试

在调试模式下运行函数。spring-doc.cadn.net.cn

./mvnw azure-functions:run -DenableDebug
// If you want to debug your functions, please add the following line
// to the azurefunctions section of your build.gradle.
azurefunctions {
  ...
  localDebug = "transport=dt_socket,server=y,suspend=n,address=5005"
}

或者,将您的JAVA_OPTS值改为local.settings.json,如下所示:spring-doc.cadn.net.cn

{
	"IsEncrypted": false,
	"Values": {
		...
		"FUNCTIONS_WORKER_RUNTIME": "java",
		"JAVA_OPTS": "-Djava.net.preferIPv4Stack=true -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=127.0.0.1:5005"
	}
}

这是一个VSCode远程调试配置的代码片段:spring-doc.cadn.net.cn

{
	"version": "0.2.0",
	"configurations": [
		{
			"type": "java",
			"name": "Attach to Remote Program",
			"request": "attach",
			"hostName": "localhost",
			"port": "5005"
		},
	]
}

函数调用器(已弃用)

FunctionInvoker编程模型已弃用,今后将不再支持。

有关函数集成方法的更多文档和示例,请参阅azure-sample README 文件和代码。spring-doc.cadn.net.cn