本指南演示了以下 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",);
final String sqlServerName = SdkContext.randomResourceName("sql",);
final String sqlDbName = SdkContext.randomResourceName("dbname",);
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() + " "
+ rst.getString());
}
} 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",);
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().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 数据库

更多精彩干货 请点击查看

欢迎有兴趣的朋友多多交流

A究院研究生 Azurecommunity@qq.com

Azure Java Libraries 入门的更多相关文章

  1. Azure .NET Libraries 入门

    本指南演示了以下 Azure .NET API 的用法,包括设置认证.创建并使用 Azure 存储.创建并使用 Azure SQL 数据库.部署虚拟机.从 GitHub 部署 Azure Web 应用 ...

  2. Azure DevOps Server 入门实践与安装部署

    一,引言 最近一段时间,公司希望在自己的服务器上安装本地版的 Azure DevOps Service(Azure DevOps Server),用于项目内的测试,学习.本着学习的目的,我也就开始学习 ...

  3. 自学 Java 怎么入门

    自学 Java 怎么入门? 595赞同反对,不会显示你的姓名     给你推荐一个写得非常用心的Java基础教程:java-basic | 天码营 这个教程将Java的入门基础知识贯穿在一个实例中,逐 ...

  4. Azure Management API 之 利用 Windows Azure Management Libraries 来控制Azure platform

    在此之前,我曾经发过一篇文章讲叙了如何利用Azure power shell team 提供的class library. 而就在这篇文章发布之后不久,我又发现微软发布了一个preview 版本的Wi ...

  5. 《JAVA 从入门到精通》 - 正式走向JAVA项目开发的路

    以前很多时候会开玩笑,说什么,三天学会PHP,七天精通Nodejs,xx天学会xx ... 一般来说,这样子说的多半都带有一点讽刺的意味,我也基本上从不相信什么快速入门.我以前在学校的时候自觉过很多门 ...

  6. Java NIO入门(二):缓冲区内部细节

    Java NIO 入门(二)缓冲区内部细节 概述 本文将介绍 NIO 中两个重要的缓冲区组件:状态变量和访问方法 (accessor). 状态变量是前一文中提到的"内部统计机制"的 ...

  7. 完成《Java编程入门》初稿

    Java编程入门 现在的运维工程师不但要懂得集合网络.系统管理而且要和开发人员一起调试系统,社会上也需要"复合性"的运维人员,所以需要做运维的也要懂一些开发,知道软件系统接口的调试 ...

  8. 三、Android NDK编程预备之Java jni入门创建C/C++共享库

    转自: http://www.eoeandroid.com/thread-264971-1-1.html 应网友回复,答应在两天前要出一篇创建C/C++共享库的,但由于清明节假期,跟朋友出去游玩,丢手 ...

  9. 二、Android NDK编程预备之Java jni入门Hello World

    转自:  http://www.eoeandroid.com/forum.php?mod=viewthread&tid=264543&fromuid=588695 昨天已经简要介绍了J ...

随机推荐

  1. 1.Javascript简介

    web前端有三层: HTML:从语义的角度,描述页面的结构 CSS:从审美的角度,描述样式(美化页面) JavaScript:从交互的角度,描述行为(提升用户体验) 历史背景介绍 布兰登 艾奇 199 ...

  2. Python 中的 10 个常见安全漏洞,以及如何避免(下)

    简评:编写安全代码很困难,当你学习一个编程语言.模块或框架时,你会学习其使用方法. 在考虑安全性时,你需要考虑如何避免被滥用,Python 也不例外,即使在标准库中,也存在用于编写应用的不良实践.然而 ...

  3. UITouch笔记

    UITouch是什么 表示在在屏幕上触摸事件,包括触摸的位置.大小.力度(3D touch).运动. 在一系列触摸事件中,UITouch都是同一个,但是不要retain某一个UITouch.如果要保存 ...

  4. 2016级算法第一次练习赛-E.AlvinZH的儿时回忆——蛙声一片

    864 AlvinZH的儿时回忆----蛙声一片 题目链接:https://buaacoding.cn/problem/865/index 思路 中等题.难点在于理解题意!仔细读题才能弄懂题目规则.整 ...

  5. Numpy中扁平化函数ravel()和flatten()的区别

    在Numpy中经常使用到的操作由扁平化操作,Numpy提供了两个函数进行此操作,他们的功能相同,但在内存上有很大的不同. 先来看这两个函数的使用: from numpy import * a = ar ...

  6. 进阶篇:2.2)DFMA运用实例

    本章目的:摘录一些DFMA运用的实例,可做参考. 1.DFMA的运用实例 DFMA提供了一个从装配和制造的角度去分析已给定设计的系统方法.采用这种方法可以使得产品结构更简单.性能更可靠.装配和制造的成 ...

  7. Linux I2C驱动--用户态驱动简单示例

    1. Linux内核支持I2C通用设备驱动(用户态驱动:由应用层实现对硬件的控制可以称之为用户态驱动),实现文件位于drivers/i2c/i2c-dev.c,设备文件为/dev/i2c-0 2. I ...

  8. vue-cli 启动过项目步骤

    一. 安装 node.js 安装完成后,可以命令行工具中输入 node -v 和 npm -v,如果能显示出版本号,就说明安装成功. 二.安装webpack npm install webpack - ...

  9. Webpack的详细配置,[Webpack中各种loader的安装配置]

    在使用webpack的时候,你是不是被以下这种报错所困扰: 注意看 黄色框中标注的 You may need an appropriate loader to handle this file typ ...

  10. linux 安装python

    wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tgz #下载安装包 tar zxvf Python-3.6.0.tgz #解压 . ...