求Azure Event Grid与Service Bus集成的Java/JavaScript函数示例
Hey there! I've got you covered with step-by-step implementations for integrating Azure Event Grid with Service Bus using both Java and JavaScript Azure Functions. Let's dive right in.
Prerequisites First
Before writing code, make sure you have these resources set up in Azure:
- An Azure Event Grid Topic (where events will be published)
- An Azure Service Bus Queue or Topic (where we'll route Event Grid events)
- An Azure Function App (configured for Java or JavaScript runtime, depending on your choice)
- Optional: Azure Functions Core Tools for local testing
Implementation 1: Java Azure Function
We'll use an Event Grid Trigger function to consume events, then use the Azure Service Bus SDK to forward them to your Service Bus queue/topic.
Step 1: Add Dependencies
In your pom.xml, include these required dependencies:
<dependencies> <!-- Azure Functions Java Library --> <dependency> <groupId>com.microsoft.azure.functions</groupId> <artifactId>azure-functions-java-library</artifactId> <version>3.0.0</version> </dependency> <!-- Azure Service Bus SDK --> <dependency> <groupId>com.azure</groupId> <artifactId>azure-messaging-servicebus</artifactId> <version>7.17.0</version> </dependency> </dependencies>
Step 2: Function Code
Here's the full function code that listens to Event Grid and sends events to Service Bus:
import com.azure.messaging.servicebus.ServiceBusClientBuilder; import com.azure.messaging.servicebus.ServiceBusSenderClient; import com.microsoft.azure.functions.ExecutionContext; import com.microsoft.azure.functions.annotation.EventGridTrigger; public class EventGridToServiceBusFunction { // Use Managed Identity or connection string (prefer Managed Identity in production) private static final String SERVICE_BUS_CONNECTION_STRING = System.getenv("SERVICE_BUS_CONNECTION_STRING"); private static final String SERVICE_BUS_QUEUE_NAME = System.getenv("SERVICE_BUS_QUEUE_NAME"); @FunctionName("EventGridToServiceBus") public void run( @EventGridTrigger(name = "event") String eventGridEvent, final ExecutionContext context) { context.getLogger().info("Received Event Grid event: " + eventGridEvent); // Send event to Service Bus try (ServiceBusSenderClient senderClient = new ServiceBusClientBuilder() .connectionString(SERVICE_BUS_CONNECTION_STRING) .buildSenderClient(SERVICE_BUS_QUEUE_NAME)) { senderClient.sendMessage(eventGridEvent); context.getLogger().info("Successfully sent event to Service Bus"); } catch (Exception e) { context.getLogger().severe("Error sending event to Service Bus: " + e.getMessage()); throw new RuntimeException("Failed to forward event to Service Bus", e); } } }
Key Notes for Java Implementation
- Configuration: Store your Service Bus connection string and queue/topic name in the Function App's Application Settings (don't hardcode them!).
- Managed Identity: For production, use a System-Assigned or User-Assigned Managed Identity instead of a connection string. Grant the
Service Bus Data Senderrole to the identity on your Service Bus resource. - Error Handling: The example uses a try-with-resources block to auto-close the Service Bus client. Add retry logic (using SDK's built-in retries or custom policies) for transient failures.
Implementation 2: JavaScript/TypeScript Azure Function
This uses an Event Grid Trigger and the @azure/service-bus npm package to forward events.
Step 1: Set Up Project
If starting from scratch, create a new JavaScript Function project with:
func init EventGridToServiceBusJS --javascript cd EventGridToServiceBusJS func new --template "Event Grid trigger" --name EventGridToServiceBus
Install the Service Bus SDK:
npm install @azure/service-bus
Step 2: Configure Function Trigger
Update function.json to ensure the trigger is set up correctly (the default template should work, but double-check):
{ "bindings": [ { "type": "eventGridTrigger", "name": "eventGridEvent", "direction": "in" } ], "scriptFile": "./index.js" }
Step 3: Function Code
Replace the content of index.js with this code:
const { ServiceBusClient } = require("@azure/service-bus"); // Get configuration from environment variables const SERVICE_BUS_CONNECTION_STRING = process.env.SERVICE_BUS_CONNECTION_STRING; const SERVICE_BUS_QUEUE_NAME = process.env.SERVICE_BUS_QUEUE_NAME; module.exports = async function (context, eventGridEvent) { context.log("Received Event Grid event:", JSON.stringify(eventGridEvent)); if (!SERVICE_BUS_CONNECTION_STRING || !SERVICE_BUS_QUEUE_NAME) { context.log.error("Service Bus connection string or queue name not configured"); throw new Error("Missing required Service Bus configuration"); } try { const serviceBusClient = new ServiceBusClient(SERVICE_BUS_CONNECTION_STRING); const sender = serviceBusClient.createSender(SERVICE_BUS_QUEUE_NAME); // Send the entire Event Grid event as a message await sender.sendMessages({ body: JSON.stringify(eventGridEvent) }); context.log("Successfully sent event to Service Bus"); // Close the sender and client await sender.close(); await serviceBusClient.close(); } catch (error) { context.log.error("Error sending event to Service Bus:", error.message); throw new Error("Failed to forward event to Service Bus", error); } };
Key Notes for JavaScript Implementation
- Environment Variables: Add
SERVICE_BUS_CONNECTION_STRINGandSERVICE_BUS_QUEUE_NAMEto your Function App's Application Settings. - Managed Identity: Just like the Java example, use Managed Identity in production. The SDK will automatically use the identity if you omit the connection string and set the
AZURE_CLIENT_IDenvironment variable (for user-assigned identity) or rely on system-assigned identity. - Async/Await: The function uses async/await for non-blocking operations, which is best practice for Node.js functions.
Additional Technical Guidance
- Event Grid Subscription: After deploying your function, create an Event Grid Subscription to your Topic, selecting the Function App as the endpoint. Make sure the function has the
Event Grid Event Receiverrole if using Managed Identity. - Testing: Use Azure CLI or the Azure Portal to send a test event to your Event Grid Topic, then check the Service Bus queue/topic to confirm the message was received.
- Scaling: Azure Functions will automatically scale based on incoming Event Grid events. Ensure your Service Bus resource is configured to handle the throughput.
- Dead-Lettering: Configure Service Bus dead-letter queues to capture events that fail to process after retries.
内容的提问来源于stack exchange,提问作者Swati Patil

