本指南演示了以下 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. TCP/IP学习笔记(3)-IP、ARP、RARP协议

    这三个协议放到一起学习是因为这三个协议处于同一层,ARP协议用来找到目标主机的Ethernet网卡Mac地址,IP则承载要发送的消息.数据链路层可以从ARP得到数据的传送信息,而从IP得到要传输的数据 ...

  2. [bzoj2816][ZJOI2012]网络(LCT,splay)

    传送门 题解 话说以前还真没见过用LCT只维护一条链的……好像除了树点涂色那题…… 先看一下题目规定的两个性质 对于任意节点连出去的边中,相同颜色的边不超过两条. 图中不存在同色的环,同色的环指相同颜 ...

  3. str中的join方法; set集合;深浅拷贝

    一.str中的join方法 1,用join可以吧列表转换为字符串 将列表转换成字符串. 每个元素之间用_拼接 s = "_". join(['德玛', ''赵信'', '易']) ...

  4. 初探 模拟退火算法 POJ2420 HDU1109

    模拟退火算法来源于固体退火原理,更多的化学物理公式等等这里不再废话,我们直接这么来看 模拟退火算法简而言之就是一种暴力搜索算法,用来在一定概率下查找全局最优解 找的过程和固体退火原理有所联系,一般来讲 ...

  5. 事件委托,元素节点操作,todolist计划列表实例

    一. 事件委托 事件委托就是利用冒泡的原理,把事件加到父级上,来代替子集执行相应的操作,事件委托首先可以极大减少事件绑定次数,提高性能:其次可以让新加入的子元素也可以拥有相同的操作. 比如有20个&l ...

  6. 大话AJAX原理

    大话AJAX原理 一.什么是Ajax Ajax(Asynchronous JavaScript and XML的缩写)是一种异步请求数据的web开发技术,对于改善用户的体验和页面性能很有帮助.简单地说 ...

  7. Saiku2.6 Saiku315 链接SQL的JDBC字符串

    Saiku26 type=OLAP name=CloudConn driver=mondrian.olap4j.MondrianOlap4jDriver location=jdbc:mondrian: ...

  8. 数组其他部分及java常见排序

    数据结构的基本概述: 数据结构是讲什么,其实大概就分为两点: 1.数据与数据之间的逻辑关系:集合.一对一.一对多.多对多 2.数据的存储结构: 一对一的:线性表:顺序表(比如:数组).链表.栈(先进后 ...

  9. git提交代码

    安装 Windows 下载安装地址 Linux 1 yum install git / apt-get install git 安装后执行,正常显示则安装正常 1 git --version 使用 生 ...

  10. python定义的一个简单的shell函数的代码

    把写代码过程中经常用到的一些代码段做个记录,如下代码段是关于python定义的一个简单的shell函数的代码. pipe = subprocess.Popen(cmd, stdout=subproce ...