本指南演示了以下 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. 不得不说fdm真的好用

    记忆力太差系列 挺好用的软件 下载器FDM真的很好用

  2. 514. Freedom Trail

    In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal ...

  3. Objective-C适用C数学函数 <math.h>

    在实际工作中有些程序不可避免的需要使用数学函数进行计算,比如地图程序的地理坐标到地图坐标的变换.Objective-C做为ANSI C的扩展,使用C标准库头文件<math.h>中定义的数学 ...

  4. [转] Linux 硬件设备查看命令

    linux查看设备命令 系统 # uname -a # 查看内核/操作系统/CPU信息 # head -n 1 /etc/issue # 查看操作系统版本 # cat /proc/cpuinfo # ...

  5. 恢复 MSSQL bak 文件扩展名数据(上)

    恢复 MSSQL bak 文件扩展名数据 一.概念: Microsoft SQL Server是由美国微软公司所推出的关系数据库解决方案,最新的版本是SQL Server 2016,已经在2016年6 ...

  6. centos6装python3,并安装requests, lxml和beautifulsoup模块

     一.  安装python3并设为默认版本,与python2共存 1.下载Python3.4安装包 wget https://www.python.org/ftp/python/3.4.4/Pytho ...

  7. 可持久化数据结构QwQ(持续更新中)

    可持久化留下的迹象 我们俯身欣赏 ——<膜你抄>By Menci&24OI Micardi最近在学可持久化的东西,可持久化线段树.可持久化并查集.可持久化01Trie......等 ...

  8. 使用Mondrian Virtual OLAP Cube 实现星座模型并在saiku展现分析

    1.什么是星座模型? 2.哪些地方可以用到星座模型? 3.Mondrian怎么构建星座模型,构建过程又涉及到哪些理论概念. 答1:这里描述了维度模型常用的 星型.雪花.星座模型,简而言之就是多事实表模 ...

  9. [转] Citrix XenDesktop桌面登录VM提示Citrix Web插件错误

    [From] http://blog.51cto.com/xuhaili100love/1223707 [适用版本] 适用所有Citrix虚拟桌面版本 [现象描述] 使用SC登录虚拟机提示“无法访问您 ...

  10. odoo 的一些orm 操作

    1.基础文件及目录结构 在认识odoo ORM框架前,先介绍一下odoo中模块目录结构.     data:存放模块预制数据 i18n:存放国际化文件 models:存放模型等py代码 securit ...