開始使用 Azure 上的 Java 進行雲端開發Get started with cloud development using Java on Azure
11/20/2020
在此文章
本文會逐步引導您設定開發環境,以便在 Java 中進行 Azure 開發。This article walks you through setting up a development environment for Azure development in Java. 然後,您將建立一些 Azure 資源並連接到這些資源,以進行一些基本工作,例如上傳檔案或部署 web 應用程式。You'll then create some Azure resources and connect to them to do some basic tasks, like uploading a file or deploying a web application. 當您完成時,您就已做好準備可以開始在自有的 Java 應用程式中使用 Azure 服務。When you're finished, you'll be ready to start using Azure services in your own Java applications.
PrerequisitesPrerequisites
一個 Azure 帳戶。An Azure account. 如果您沒有帳戶,請取得免費試用帳戶。If you don't have one, get a free trial.
Java 8 (包含在 Azure Cloud Shell 中)。Java 8, which is included in Azure Cloud Shell.
Maven 3 (包含在 Azure Cloud Shell 內)。Maven 3, which is included in Azure Cloud Shell.
設定驗證Set up authentication
Java 應用程式必須有 Azure 訂用帳戶的讀取和建立權限,才能在此教學課程中執行程式碼範例。Your Java application needs read and create permissions in your Azure subscription to run the sample code in this tutorial. 請建立服務主體,並將應用程式設定為使用其認證來執行。Create a service principal, and configure your application to run with its credentials. 服務主體可讓您建立與身分識別相關聯的非互動式帳戶,而且對於此身分識別,您只賦予它應用程式執行時所需的權限。Service principals provide a way to create a noninteractive account associated with your identity to which you grant only the privileges your app needs to run.
az ad sp create-for-rbac --name AzureJavaTest
這會提供您下列格式的回覆:Which gives you a reply in the following format:
{
"appId": "a487e0c1-82af-47d9-9a0b-af184eb87646d",
"displayName": "AzureJavaTest",
"name": "http://AzureJavaTest",
"password": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
"tenant": "tttttttt-tttt-tttt-tttt-tttttttttttt"
}
接下來,設定環境變數:Next, configure the environment variables:
AZURE_SUBSCRIPTION_ID:使用在 Azure CLI 2.0 中透過 az account show 所得到的 id 值。AZURE_SUBSCRIPTION_ID: Use the id value from az account show in the Azure CLI 2.0.
AZURE_CLIENT_ID:使用從服務主體輸出所擷取的 appId 值。AZURE_CLIENT_ID: Use the appId value from the output taken from a service principal output.
AZURE_CLIENT_SECRET:使用從服務主體輸出所得到的 password 值。AZURE_CLIENT_SECRET: Use the password value from the service principal output.
AZURE_TENANT_ID:使用從服務主體輸出所得到的 tenant 值。AZURE_TENANT_ID: Use the tenant value from the service principal output.
ToolingTooling
建立新的 Maven 專案Create a new Maven project
注意
本文使用 Maven 建置工具來建置和執行範例程式碼。This article uses the Maven build tool to build and run the sample code. 其他 build tools (例如 Gradle)也可以使用 Azure SDK for JAVA。Other build tools, such as Gradle, also work with the Azure SDK for Java.
透過命令列在系統上的新目錄中建立 Maven 專案。Create a Maven project from the command line in a new directory on your system.
mkdir java-azure-test
cd java-azure-test
mvn archetype:generate -DgroupId=com.fabrikam -DartifactId=AzureApp \
-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
此步驟會在 testAzureApp 目錄下建立基本的 Maven 專案。This step creates a basic Maven project under the testAzureApp directory. 在專案的 pom.xml 檔案中新增下列專案,以匯入本教學課程的範例程式碼中所使用的程式庫。Add the following entries into the project's pom.xml file to import the libraries used in the sample code in this tutorial.
com.azure
azure-identity
1.2.0
com.azure.resourcemanager
azure-resourcemanager
2.1.0
com.azure
azure-storage-blob
12.8.0
com.microsoft.sqlserver
mssql-jdbc
6.2.1.jre8
在最上層 project 元素底下新增 build 項目以使用 maven-exec-plugin 來執行這些範例。Add a build entry under the top-level project element to use the maven-exec-plugin to run the samples.
org.codehaus.mojo
exec-maven-plugin
com.fabrikam.AzureApp
安裝 Azure Toolkit for IntellijInstall the Azure Toolkit for Intellij
如果您打算以程式設計方式部署 Web 應用程式或 API,則需要 Azure 工具組。The Azure toolkit is necessary if you plan to deploy web apps or APIs programmatically. 其目前不會用於任何其他種類的開發。Currently, it isn't used for any other kinds of development. 下列步驟會摘要說明安裝程序。The following steps summarize the installation process.
選取 [檔案] 功能表,然後選取 [設定]。Select the File menu, and then select Settings.
選取 [瀏覽存放庫] 並搜尋 Azure,然後安裝 Azure Toolkit for Intellij。Select Browse repositories, and then search Azure and install the Azure toolkit for Intellij.
重新啟動 Intellij。Restart Intellij.
安裝適用於 Eclipse 的 Azure 工具組Install the Azure Toolkit for Eclipse
如果您打算以程式設計方式部署 Web 應用程式或 API,則需要 Azure 工具組。The Azure toolkit is necessary if you plan to deploy web apps or APIs programmatically. 其目前不會用於任何其他種類的開發。Currently, it isn't used for any other kinds of development. 下列步驟會摘要說明安裝程序。The following steps summarize the installation process.
選取 [說明] 功能表,然後選取 [安裝新軟體]。Select the Help menu, and then select Install new software.
在 [使用] 方塊中,輸入 http://dl.microsoft.com/eclipse/,然後選取 Enter。In the Work with box, enter http://dl.microsoft.com/eclipse/ and select Enter.
選取 [Azure toolkit for Java] 旁的核取方塊。Select the check box next to Azure toolkit for Java. 清除 [在安裝期間連絡所有更新網站來尋找必要軟體] 的核取方塊。Clear the check box for Contact all update sites during install to find required software. 然後選取 [下一步]。Then select Next.
建立 Linux 虛擬機器Create a Linux virtual machine
在專案的 src/main/java/com/fabrikam 目錄中建立名為 >azureapp.java 的新檔案,並貼上下列程式碼區塊。Create a new file named AzureApp.java in the project's src/main/java/com/fabrikam directory, and paste in the following block of code. 使用機器的實際值來更新 userName 和 sshKey 變數。Update the userName and sshKey variables with real values for your machine. 此程式碼會在美國東部 Azure 區域執行的 sampleResourceGroup 資源群組中,建立名為 testLinuxVM 的新 Linux 虛擬機器 (VM)。The code creates a new Linux virtual machine (VM) with the name testLinuxVM in the resource group sampleResourceGroup running in the US East Azure region.
package com.fabrikam;
import com.azure.core.credential.TokenCredential;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.Region;
import com.azure.core.management.profile.AzureProfile;
import com.azure.identity.AzureAuthorityHosts;
import com.azure.identity.EnvironmentCredentialBuilder;
import com.azure.resourcemanager.AzureResourceManager;
import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage;
import com.azure.resourcemanager.compute.models.VirtualMachine;
import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes;
public class AzureApp {
public static void main(String[] args) {
final String userName = "YOUR_VM_USERNAME";
final String sshKey = "YOUR_PUBLIC_SSH_KEY";
try {
TokenCredential credential = new EnvironmentCredentialBuilder()
.authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)
.build();
// If you don't set the tenant ID and subscription ID via environment variables,
// change to create the Azure profile with tenantId, subscriptionId, and Azure environment.
AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
AzureResourceManager azureResourceManager = AzureResourceManager.configure()
.withLogLevel(HttpLogDetailLevel.BASIC)
.authenticate(credential, profile)
.withDefaultSubscription();
// Create an Ubuntu virtual machine in a new resource group.
VirtualMachine linuxVM = azureResourceManager.virtualMachines().define("testLinuxVM")
.withRegion(Region.US_EAST)
.withNewResourceGroup("sampleVmResourceGroup")
.withNewPrimaryNetwork("10.0.0.0/24")
.withPrimaryPrivateIPAddressDynamic()
.withoutPrimaryPublicIPAddress()
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername(userName)
.withSsh(sshKey)
.withUnmanagedDisks()
.withSize(VirtualMachineSizeTypes.STANDARD_D3_V2)
.create();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
從命令列執行範例。Run the sample from the command line.
mvn compile exec:java
您會在主控台中看到某些 REST 要求和回應,因為 SDK 會對 Azure REST API 進行基礎呼叫,以設定 VM 和其資源。You'll see some REST requests and responses in the console as the SDK makes the underlying calls to the Azure REST API to configure the VM and its resources. 程式完成後,請使用 Azure CLI 2.0 在訂用帳戶中確認 VM。After the program finishes, verify the VM in your subscription with the Azure CLI 2.0.
az vm list --resource-group sampleVmResourceGroup
在確認程式碼有效後,請使用 CLI 來刪除 VM 和其資源。After you've verified that the code worked, use the CLI to delete the VM and its resources.
az group delete --name sampleVmResourceGroup
從 GitHub 存放庫部署 Web 應用程式Deploy a web app from a GitHub repo
將 AzureApp.java 中的 main方法取代成下列內容。Replace the main method in AzureApp.java with the following one. 執行程式碼之前,請先將 appName 變數更新為唯一值。Update the appName variable to a unique value before you run the code. 此程式碼會將公用 GitHub 存放庫中 master 分支內的 Web 應用程式,部署至執行於免費定價層的新的 Azure App Service Web 應用程式。This code deploys a web application from the master branch in a public GitHub repo into a new Azure App Service Web App running in the free pricing tier.
public static void main(String[] args) {
try {
final String appName = "YOUR_APP_NAME";
TokenCredential credential = new EnvironmentCredentialBuilder()
.authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)
.build();
// If you don't set the tenant ID and subscription ID via environment variables,
// change to create the Azure profile with tenantId, subscriptionId, and Azure environment.
AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
AzureResourceManager azureResourceManager = AzureResourceManager.configure()
.withLogLevel(HttpLogDetailLevel.BASIC)
.authenticate(credential, profile)
.withDefaultSubscription();
WebApp app = azureResourceManager.webApps().define(appName)
.withRegion(Region.US_WEST2)
.withNewResourceGroup("sampleWebResourceGroup")
.withNewWindowsPlan(PricingTier.FREE_F1)
.defineSourceControl()
.withPublicGitRepository(
"https://github.com/Azure-Samples/app-service-web-java-get-started")
.withBranch("master")
.attach()
.create();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
使用 Maven 如往常一樣地執行程式碼。Run the code as before using Maven.
mvn clean compile exec:java
使用 CLI 開啟瀏覽器並讓其指向該應用程式。Open a browser pointed to the application by using the CLI.
az appservice web browse --resource-group sampleWebResourceGroup --name YOUR_APP_NAME
確認過部署後,請從訂用帳戶中移除 Web 應用程式和方案。Remove the web app and plan from your subscription after you've verified the deployment.
az group delete --name sampleWebResourceGroup
連線到 Azure SQL 資料庫Connect to an Azure SQL database
使用下列程式碼取代 AzureApp.java 中目前的 main 方法。Replace the current main method in AzureApp.java with the following code. 為變數設定實際值。Set real values for the variables.
此程式碼會使用允許遠端存取的防火牆規則來建立新的 SQL 資料庫。This code creates a new SQL database with a firewall rule that allows remote access. 然後,程式碼會使用 SQL Database JBDC 驅動程式來與之連線。Then the code connects to it by using the SQL Database JBDC driver.
public static void main(String args[])
{
// Create the db using the management libraries.
try {
TokenCredential credential = new EnvironmentCredentialBuilder()
.authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)
.build();
// If you don't set the tenant ID and subscription ID via environment variables,
// change to create the Azure profile with tenantId, subscriptionId, and Azure environment.
AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
AzureResourceManager azureResourceManager = AzureResourceManager.configure()
.withLogLevel(HttpLogDetailLevel.BASIC)
.authenticate(credential, profile);
final String adminUser = "YOUR_USERNAME_HERE";
final String sqlServerName = "YOUR_SERVER_NAME_HERE";
final String sqlDbName = "YOUR_DB_NAME_HERE";
final String dbPassword = "YOUR_PASSWORD_HERE";
final String firewallRuleName = "YOUR_RULE_NAME_HERE";
SqlServer sampleSQLServer = azureResourceManager.sqlServers().define(sqlServerName)
.withRegion(Region.US_EAST)
.withNewResourceGroup("sampleSqlResourceGroup")
.withAdministratorLogin(adminUser)
.withAdministratorPassword(dbPassword)
.defineFirewallRule(firewallRuleName)
.withIpAddressRange("0.0.0.0","255.255.255.255")
.attach()
.create();
SqlDatabase sampleSQLDb = sampleSQLServer.databases().define(sqlDbName).create();
// Assemble the connection string to the database.
final String domain = sampleSQLServer.fullyQualifiedDomainName();
String url = "jdbc:sqlserver://"+ domain + ":1433;" +
"database=" + sqlDbName +";" +
"user=" + adminUser+ "@" + sqlServerName + ";" +
"password=" + dbPassword + ";" +
"encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
// Connect to the database, create a table, and insert an entry into it.
Connection conn = DriverManager.getConnection(url);
String createTable = "CREATE TABLE CLOUD ( name varchar(255), code int);";
String insertValues = "INSERT INTO CLOUD (name, code ) VALUES ('Azure', 1);";
String selectValues = "SELECT * FROM CLOUD";
Statement createStatement = conn.createStatement();
createStatement.execute(createTable);
Statement insertStatement = conn.createStatement();
insertStatement.execute(insertValues);
Statement selectStatement = conn.createStatement();
ResultSet rst = selectStatement.executeQuery(selectValues);
while (rst.next()) {
System.out.println(rst.getString(1) + " "
+ rst.getString(2));
}
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getStackTrace().toString());
}
}
從命令列執行範例。Run the sample from the command line.
mvn clean compile exec:java
然後使用 CLI 清除資源。Then clean up the resources by using the CLI.
az group delete --name sampleSqlResourceGroup
將 blob 寫入新的儲存體帳戶中Write a blob into a new storage account
使用下列程式碼取代 AzureApp.java 中目前的 main 方法。Replace the current main method in AzureApp.java with the following code. This code creates an Azure storage account. 然後,程式碼會使用適用於 Java 的 Azure 儲存體程式庫在雲端建立新的文字檔。Then the code uses the Azure Storage libraries for Java to create a new text file in the cloud.
public static void main(String[] args) {
try {
TokenCredential tokenCredential = new EnvironmentCredentialBuilder()
.authorityHost(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD)
.build();
// If you don't set the tenant ID and subscription ID via environment variables,
// change to create the Azure profile with tenantId, subscriptionId, and Azure environment.
AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
AzureResourceManager azureResourceManager = AzureResourceManager.configure()
.withLogLevel(HttpLogDetailLevel.BASIC)
.authenticate(tokenCredential, profile)
.withDefaultSubscription();
// Create a new storage account.
String storageAccountName = "YOUR_STORAGE_ACCOUNT_NAME_HERE";
StorageAccount storage = azureResourceManager.storageAccounts().define(storageAccountName)
.withRegion(Region.US_WEST2)
.withNewResourceGroup("sampleStorageResourceGroup")
.create();
// Create a storage container to hold the file.
List keys = storage.getKeys();
PublicEndpoints endpoints = storage.endPoints();
String accountName = storage.name();
String accountKey = keys.get(0).value();
String endpoint = endpoints.primary().blob();
StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey);
BlobServiceClient storageClient =new BlobServiceClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildClient();
// Container name must be lowercase.
BlobContainerClient blobContainerClient = storageClient.getBlobContainerClient("helloazure");
blobContainerClient.create();
// Make the container public.
blobContainerClient.setAccessPolicy(PublicAccessType.CONTAINER, null);
// Write a blob to the container.
String fileName = "helloazure.txt";
String textNew = "Hello Azure";
BlobClient blobClient = blobContainerClient.getBlobClient(fileName);
InputStream is = new ByteArrayInputStream(textNew.getBytes());
blobClient.upload(is, textNew.length());
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
從命令列執行範例。Run the sample from the command line.
mvn clean compile exec:java
您可以透過 Azure 入口網站或使用 Azure 儲存體總管,在您的儲存體帳戶中流覽 helloazure.txt 檔案。You can browse for the helloazure.txt file in your storage account through the Azure portal or with Azure Storage Explorer.
使用 CLI 清除儲存體帳戶。Clean up the storage account by using the CLI.
az group delete --name sampleStorageResourceGroup
探索更多範例Explore more samples
若要深入了解如何使用適用於 Java 的 Azure 管理程式庫來管理資源和自動執行工作,請參閱我們針對虛擬機器、Web 應用程式和 SQL 資料庫所提供的程式碼範例。To learn more about how to use the Azure management libraries for Java to manage resources and automate tasks, see our sample code for virtual machines, web apps, and SQL database.
參考資料和版本資訊Reference and release notes
我們針對所有套件提供了參考資料。A reference is available for all packages.
獲得協助及提供意見Get help and give feedback
Post questions to the community on Stack Overflow. 針對 GitHub 存放庫中的 Azure SDK for JAVA 回報 bug 和開啟問題。Report bugs and open issues against the Azure SDK for Java in the GitHub repository.