Azure Java Libraries 入门

本指南演示了以下 Azure Java Libraries 的用法,包括设置认证、创建并使用 Azure 存储、创建并使用 Azure SQL 数据库、部署虚拟机、从 GitHub 部署 Azure Web 应用。在本教程中完成的所有操作均符合1 元试用条件。

本指南演示了以下 Azure Java Libraries 的用法,包括设置认证、创建并使用 Azure 存储、创建并使用 Azure SQL 数据库、部署虚拟机、从 GitHub 部署 Azure Web 应用。在本教程中完成的所有操作均符合1 元试用条件

开始之前

如果您还没有 Azure 账户,可以申请 1 元试用账户。

Azure CLI 2.0

Java 8

Maven 3

设置认证

为了使用 Azure .NET Management Libraires , 您创建的应用程序需要权限来读取和创建 Azure 订阅中的资源。我们首先需要为应用程序创建一个 service principal , service principal 可以通过非交互方式授予应用程序所需的权限。

1. 运行以下 CLI 命令登陆中国区 Azure:

az cloud set --name AzureChinaCloud

2. 运行以下命令登陆 Azure, 替换其中的账号和密码:

az login -u <account email> -p <account password>

3. 运行以下命令为 Java 应用程序创建 service principal:

az ad sp create-for-rbac --name AzureJavaTest --password "MY_SECURE_PASSWORD"

4. 创建一个名为 Azureauth.properties 的 txt 文件,输入以下内容:

# sample management library properties file
subscription=<your_subscription_id>
client=<your_client_id>
key=<your_password_id>
tenant=<your_tenant_id>
managementURI=https://management.core.chinacloudapi.cn/
baseURL=https://management.chinacloudapi.cn/
authURL=https://login.chinacloudapi.cn/
graphURL=https://graph.chinacloudapi.cn/

  • subscription: 2 中记录的 id
  • client: 3 中记录的 appId
  • key: 3 中的 -password 参数值
  • tenant: 2 中记录的 TenantId

5. 保存 Azureauth.properties,将 Azureauth.properties 的存放路径设置为环境变量 AZURE_AUTH_LOCATION。

创建新的 Maven 项目

运行以下命令创建 Maven 项目

mkdir java-azure-test
cd java-azure-test
mvn archetype:generate -DgroupId=com.fabrikam -DartifactId=testAzureApp  
-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

运行完成后显示结果如下:

这样我们就在 testAzureApp 文件夹下创建了一个 Maven 项目,现在我们需要在 pom.xml 中的 dependencies 元素下添加以下内容用来导入本教程中所使用的 Java Azure Libraries。

<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-storage</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.2.1.jre8</version>
</dependency>

 同样的,在 project 元素下添加以下 build 内容:

<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<mainClass>com.fabrikam.testAzureApp.AzureApp</mainClass>
</configuration>
</plugin>
</plugins>
</build>

创建虚拟机

在 testAzureApp 项目的 src/main/java 路径下创建一个 AzureApp.java 文件,在文件中添加以下代码,将 userName 和 sshKey 变量的值替换成您使用的值。

package com.fabrikam.testAzureApp;
import com.microsoft.azure.management.Azure;
import com.microsoft.azure.management.compute.VirtualMachine;
import com.microsoft.azure.management.compute.KnownLinuxVirtualMachineImage;
import com.microsoft.azure.management.compute.VirtualMachineSizeTypes;
import com.microsoft.azure.management.appservice.WebApp;
import com.microsoft.azure.management.storage.StorageAccount;
import com.microsoft.azure.management.storage.SkuName;
import com.microsoft.azure.management.storage.StorageAccountKey;
import com.microsoft.azure.management.sql.SqlDatabase;
import com.microsoft.azure.management.sql.SqlServer;
import com.microsoft.azure.management.resources.fluentcore.arm.Region;
import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext;
import com.microsoft.rest.LogLevel;
import com.microsoft.azure.storage.*;
import com.microsoft.azure.storage.blob.*;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class AzureApp {
public static void main(String[] args) {
final String userName = "testUser";
final String sshKey = "Your SSH Public Key";
try {
// use the properties file with the service principal information to authenticate
// change the name of the environment variable if you used a different name in the previous step
final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION")); 
Azure azure = Azure.configure()
.withLogLevel(LogLevel.BASIC)
.authenticate(credFile)
.withDefaultSubscription();
// create a Ubuntu virtual machine in a new resource group 
VirtualMachine linuxVM = azure.virtualMachines().define("testLinuxVM")
.withRegion(Region.ChinaNorth)
.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();
}
}
}

在命令行中运行以上示例:

mvn compile exec:java

运行成功后结果如下:

发布完成后你可以使用 Azure CLI 2.0 在你的订阅下验证该虚拟机。

az vm list --resource-group sampleVmResourceGroup

验证完成后你可以删除该资源和资源组。

az group delete --name sampleVmResourceGroup

从 Github repo 部署 Web 应用

用下面的代码替换 AzureApp.java 中的 main 方法。修改变量 appName 。在运行代码前要保证 appName 在系统中是唯一的。

这个代码可以把 Github public repo 的 master branch 中的一个 Web 应用发布到一个新的 Azure App Service Web App 。

public static void main(String[] args) {
try {
final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));
final String appName = "YOUR_APP_NAME";
Azure azure = Azure.configure()
.withLogLevel(LogLevel.BASIC)
.authenticate(credFile)
.withDefaultSubscription();
WebApp app = azure.webApps().define(appName)
.withRegion(Region.CHINA_NORTH)
.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();
}
}

在命令行中运行以上示例:

mvn compile exec:java

用 CLI 打开浏览器指向该应用:

az appservice web browse --resource-group sampleWebResourceGroup --name YOUR_APP_NAME

运行成功后结果如下:

在你验证部署成功后删除该应用:

az group delete --name sampleWebResourceGroup

创建一个 SQL 数据库

用下面的代码替换 AzureApp.java 中的 main 方法。给变量 dbPassword 设置一个真实的值。

这段代码创建一个允许远程访问的数据库,并用 SQL Database JBDC driver 连接到它。

public static void main(String args[])
{
// create the db using the management libraries
try {
final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));
Azure azure = Azure.configure()
.withLogLevel(LogLevel.BASIC)
.authenticate(credFile)
.withDefaultSubscription();
final String adminUser = SdkContext.randomResourceName("db",8);
final String sqlServerName = SdkContext.randomResourceName("sql",10);
final String sqlDbName = SdkContext.randomResourceName("dbname",8);
final String dbPassword = "YOUR_PASSWORD_HERE";
SqlServer sampleSQLServer = azure.sqlServers().define(sqlServerName)
.withRegion(Region.CHINA_NORTH)
.withNewResourceGroup("sampleSqlResourceGroup")
.withAdministratorLogin(adminUser)
.withAdministratorPassword(dbPassword)
.withNewFirewallRule("0.0.0.0","255.255.255.255")
.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.chinacloudapi.cn;loginTimeout=30;";
// connect to the database, create a table and insert a 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());
}
}

用命令行运行下列代码:

mvn clean compile exec:java

运行成功后结果如下:

然后用 CLI 删除资源组。

az group delete --name sampleSqlResourceGroup

把一个 blob 写进一个新的 Storage 账户

用下面的代码替换 AzureApp.java 中的 main 方法。这段代码创建一个新的 Azure Storage 账户,并用 Azure Storage Java 库在云端创建一个新的文本文件。

public static void main(String[] args) {
try {
// use the properties file with the service principal information to authenticate
// change the name of the environment variable if you used a different name in the previous step
final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));
Azure azure = Azure.configure()
.withLogLevel(LogLevel.BASIC)
.authenticate(credFile)
.withDefaultSubscription();
// create a new storage account
String storageAccountName = SdkContext.randomResourceName("st",8);
StorageAccount storage = azure.storageAccounts().define(storageAccountName)
.withRegion(Region.CHINA_NORTH)
.withNewResourceGroup("sampleStorageResourceGroup")
.create();
// create a storage container to hold the file
List<StorageAccountKey> keys = storage.getKeys();
final String storageConnection = "DefaultEndpointsProtocol=https;"
+ "AccountName=" + storage.name()
+ ";AccountKey=" + keys.get(0).value()
+ ";EndpointSuffix=core.chinacloudapi.cn";
CloudStorageAccount account = CloudStorageAccount.parse(storageConnection);
CloudBlobClient serviceClient = account.createCloudBlobClient();
// Container name must be lower case.
CloudBlobContainer container = serviceClient.getContainerReference("helloazure");
container.createIfNotExists();
// Make the container public
BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
containerPermissions.setPublicAccess(BlobContainerPublicAccessType.CONTAINER);
container.uploadPermissions(containerPermissions);
// write a blob to the container
CloudBlockBlob blob = container.getBlockBlobReference("helloazure.txt");
blob.uploadText("hello Azure");
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}

用命令行运行下列代码: 

mvn clean compile exec:java

运行成功后结果如下:

使用 Azure portal 或者 Azure Storage Explorer,你可以在 Storage 账户中看到 helloazure.txt 文件

然后用 CLI 删除资源组。

az group delete --name sampleStorageResourceGroup

后续步骤

更多 Azure Java 示例:

虚拟机

Web 应用

SQL 数据库

原文地址:https://www.cnblogs.com/zangdalei/p/7428211.html