本指南演示了以下 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. 2018版OCP考试052最新题库及答案-35题

    35.Your database is using Automatic Memory Management. Which two SGA components must be managed manu ...

  2. ocp题库变化,052新加的考试题及答案整理-32

    32. Examine these commands and their output: • SQL> SELECT * FROM emp; • ENO ENAME • ---- ----- • ...

  3. “全栈2019”Java第七十三章:外部类里多个静态非静态内部类详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...

  4. 使用单个httpclient实例请求数据。

    做J2EE的都知道httpclient这个工具,Android也自带这个工具,不过和J2EE上的不一样,可能是google在添加的时候,自己修改了一部分代码. 在J2EE中可以使用如下代码,在多线程的 ...

  5. 游戏1:HTML5制作网页游戏围住神经猫--createjs

    游戏简介:点击小圆圈,是蓝色的小圆圈不跑出圆圈外,跑出则结束游戏 准备工作: 下载easejs  :下载地址:http://www.createjs.cc/easeljs    中文网站 效果: in ...

  6. [BZOJ 4890][TJOI2017]城市

    传送门 $ \color{green} {solution : }$ 我们可以暴力枚举断边,然后 $ O(n) $ 的跑一次换根 $ dp $,然后复杂度是 $ O(n * n) $ 的 #inclu ...

  7. 浅析PHP反序列化漏洞之PHP常见魔术方法(一)

    作为一个学习web安全的菜鸟,前段时间被人问到PHP反序列化相关的问题,以前的博客中是有这样一篇反序列化漏洞的利用文章的.但是好久过去了,好多的东西已经记得不是很清楚.所以这里尽可能写一篇详细点的文章 ...

  8. 2019.4.18 HTML + CSS相关整理

    目录 标签 块标签 行标签 行块转化 嵌套规则 css引入方式 行间样式 内部引入 外部引入 选择器 基础选择器 组合选择器 盒模型 css样式 字体属性 设置字体的大小 设置字体的粗细 设置字体的风 ...

  9. 《The One 团队》第二次作业:团队项目选题

    项目 内容 作业所属课程 http://www.cnblogs.com/nwnu-daizh/ 作业要求 https://www.cnblogs.com/nwnu-daizh/p/10726884.h ...

  10. Which mb sdconnect c4 worth the money?

    MB SD connect C4 with laptop v2018.5 Version avaiable now ,It is ready to work after you get it ,wor ...