代码改变世界

“Velocity”项目简介

2012-05-08 17:41  田志良  阅读(1001)  评论(0编辑  收藏  举报

http://msdn.microsoft.com/zh-cn/library/ee851751.aspx

“Velocity”项目简介

此主题尚未评级 - 评价此主题
 

概述

从磁盘或数据库中反复检索数据可能是应用程序的一个瓶颈。Microsoft Distributed Caching Service(代号为“Velocity”)提供了一种方法来在内存型缓存中存储数据,以供将来检索,消除了对从磁盘或数据存储器获取数据的需求。这可以显著提高应用程序的性能。此外,Velocity 还支持缓存服务群集,这可以提高应用程序的可伸缩性。

目标

在本次动手实验中,您将学习如何:

•              安装和配置 Velocity

•              基于Velocity API 的程序

•              在 ASP.NET 中使用 Velocity 的 SessionState 提供程序

               

系统要求

您必须拥有以下工具才能完成本实验:

•             Microsoft Visual Studio 2010

•             MicrosoftDistributedCache-i386.msi

注意:Vista 可能需要您对其他提示进行确认,具体取决于您的安全设置。实验说明中将忽略这些提示。

               

安装

使用 Configuration Wizard 验证本实验的所有先决条件。要确保正确配置所有内容,请按照以下步骤进行。

注意:要执行安装步骤,您需要使用管理员权限在命令行窗口中运行脚本。

 

1.            如果之前没有执行,运行 Training Kit 的 Configuration Wizard。为此,运行位于 %TrainingKitInstallationFolder%\Labs\IntroToProjectVelocity\Setup 文件夹下的 CheckDependencies.cmd 脚本。安装先决条件中没有安装的软件(如有必要请重新扫描),并完成向导。

注意: 为了方便,本实验中管理的许多代码都可用于 Visual Studio 代码片段。CheckDependencies.cmd 文件启动 Visual Studio 安装程序文件安装该代码片段。

 

               

练习

本次动手实验由以下练习组成:

1.            安装和运行 Velocity

2.            直接基于 Velocity 编程,将 Velocity 作为泛型对象缓存

3.            在 ASP.NET 中使用 Velocity 的 SessionState 提供程序

4.            各种类型的 Velocity 缓存

               

 如果我束手无策了怎么办?

该动手实验中的源代码包括一个最终文件夹,如果完成了每个练习的每一步,您可以在该文件夹中找到应该获取的 Visual Studio 解决方案。如果需要其他帮助来完成练习,您可以使用该解决方案作为指南。

 

完成本实验的估计时间:120 分钟。

               

下一步:

练习 1:安装和运行 Velocity

               

练习 1:安装和运行 Velocity

在本练习中,您将学习如何安装和配置 Velocity。

注意:   要执行这些步骤,您需要本地管理员权限。

 

安装

您必须执行以下步骤来为本实验做好准备。

1.            通过以下链接下载 Velocity Community Technology Preview 安装包 MicrosoftDistributedCache-i386.msi:http://www.microsoft.com/downloads/details.aspx?FamilyId=B24C3708-EEFF-4055-A867-19B5851E7CD2&displaylang=en

2.            将 MicrosoftDistributedCache-i386.msi 保存到 C:\VS2010TrainingKit

3.            在本地 PC 上创建 C:\VelocityLab 文件夹。

4.            将该文件夹共享为 \\localhost\VelocityLab

 

任务 1 –安装 Velocity

在本任务中,您将安装 Velocity 服务并设置默认设置。

5.            在 Windows Explorer 中双击 C:\VS2010TrainingKit\MicrosoftDistributedCache-i386.msi 运行它

6.            将出现欢迎屏幕。单击 Next。

 

 

图 1

欢迎安装屏幕

7.            出现 End User License Agreement 屏幕。如果接受许可证协议,请单击“I accept the terms in the license agreement”单选按钮。单击 Next。

 

图 2

许可协议

8.       将出现“Ready To Install”屏幕。接受默认位置 (C:\Program Files\Microsoft Distributed Cache) 并单击 Install。

 

图 3

Ready to Install 屏幕

 

9.            在安装过程中,将提示您允许以下应用程序通过防火墙。单击 OK 确认此操作。

 

图 4

允许应用程序通过防火墙

 

10.          安装之后,将出现 Cache Host Configuration 屏幕。配置以下参数:

◦              对于 Storage 位置类型,选择 Shared network folder。

◦              对于 Network path,键入“\\VS2010Labs\VelocityLab”。将 VS2010Labs 更改为本地机器的网络名称。

◦              接受 Service Port Number、Cluster Port Number 和 Max Cached Data Size 的默认值。

 

图 5

Cache Host Configuration

 

11.          要创建群集,单击 Test Connection。出现确认提示后;单击 yes 创建群集。

 

图 6

确认对话框

 

12.          创建群集后,将启用所有剩余控件,以继续配置 Cache Host。设置以下参数以完成配置过程:

◦              在 Cluster Name 处,键入“Cluster1。”

◦              在 Cluster Size 处,选择 Small (1-4) 单选按钮。

 

图 7

Cache Host Configuration

 

13.          单击 Save & Close。

14.          出现一个汇总屏幕。单击 Finish 按钮。

 

图 8

汇总屏幕

 

               

任务 2 –启动 Velocity 群集

Microsoft Velocity 随带了一个命令行管理工具,用于管理群集和缓存。使用该工具启动 Velocity 群集。

1.            启动 Velocity Administration 工具。导航到 Start | All Programs | Microsoft Distributed Cache | Administration Tool - Microsoft Distributed Cache。出现 Velocity Administration Tool。

注意:在 Microsoft Windows Vista 和 Microsoft Windows Server 2008 操作系统中,您必须右键单击 "Velocity" PowerShell 快捷方式并选择 Run as administrator 才能使缓存管理工具正常运行。

 

 

图 9

Velocity Administration Tool

 

2.            键入“Get-CacheHelp”查看列表和所有可用 Velocity cmdlets 的简要描述。

 

图 10

帮助命令

 

3.            键入“get-cachehost”查看刚才安装的主机服务的状态。

注意:The service status is “DOWN” indicating that the service is not yet started.

 

4.            键入“start-cachecluster”启动群集。

 

图 11

启动缓存群集

               

下一步:

练习 1:验证

               

练习 1:验证

要验证是否正确执行了所有练习的步骤,执行以下步骤:

验证 1:验证服务是否启动

通过本验证,您将可以确保正确启动了群集。

确认存在 Velocity 服务并且已经启动。

打开 Services Applet。

1.            导航到 Start | Control Panel。将出现控制面板。

2.            单击 Classic View 显示控制面板小程序列表。

3.            双击 Administrative Tools 图标。出现 Administrative Tools 小程序列表。

4.       双击 Services 图标。找到名为 Microsoft project code named “Velocity”的服务。其状态应该为“Started”。

 

图 12

检查服务是否正常运行

 

               

验证 2:群集正在运行

通过本验证,您将可以确保正确启动了群集。

1.            启动 Velocity Administration 工具。导航到 Start | All Programs | Microsoft Distributed Caches | Administration Tool - Microsoft Distributed

Cache。

2.            键入“get-cachehost”。确认至少列出了一个主机且状态为“SERVICE_UP”。

 

图 13

检查缓存主机的 Service Status 是否为 SERVICE UP

 

下一步:

练习 2:直接基于 Velocity 编程,将 Velocity 作为泛型对象缓存

               

练习 2:直接基于 Velocity 编程,将 Velocity 作为泛型对象缓存

本练习展示开发人员如何直接基于 Velocity 缓存编程,以缓存任何可序列化的 .NET 对象。

注意:要验证每个步骤是否正确执行,建议在每次任务结束时构建解决方案。

 

任务 1 –创建使用 Velocity 的 Windows 窗体项目。

在本任务中,您将创建一个 Windows 窗体应用程序,让缓存 API 可用于该应用程序。

1.            从 Start | All Programs | Microsoft Visual Studio 2010 | Microsoft Visual Studio 2010 打开 Microsoft Visual Studio 2010。

2.            选择 File | New Project。出现 New Project 对话框。

 

图 14

New Project 对话框

a.            从 Project Type 树中选择 Visual Basic | Web 或 Visual C# | Web。

b.            从 Templates 列表中选择 ASP.NET Web Application。

c.             在 Name 文本框中,输入揇emoVelocity1”

d.            将创建一个 New Web 窗体项目。

3.            添加对缓存库的引用

a.       在 Visual Studio 中打开 DemoVelocity1 项目,选择 Project | Add Reference…,将出现 Add References 对话框。 

b.            选择 Browse 选项卡。

 

图 15

添加引用

 

c.             打开 %ProgramFiles%\Microsoft Distributed Cache\V1.0 文件夹并选择 CacheBaseLibrary.dll 和 ClientLibrary.dll。单击 OK 按钮添加对这些库的引用。

4.            对 Web.Config 做出以下更改:

a.            在配置部分中添加以下声明:

XML

<configSections>

<section name="dataCacheClient" type="Microsoft.Data.Caching.DataCacheClientSection, CacheBaseLibrary" allowLocation="true" allowDefinition="Everywhere"/>

</configSections>

 

注意: 这将告知应用程序如何解析 web.config 缓存和日志部分中的信息

 

b.            将以下代码添加到“configSections”组之后的“configuration”部分:

XML

<dataCacheClient deployment="simple">

<localCache isEnabled="true" sync="TTLBased" ttlValue="300" />

                                <hosts>

                                                <host name="localhost" cachePort="22233" cacheHostName="DistributedCacheService"/>

                                </hosts>

</dataCacheClient>

 

注意:这些部分将为 web 应用程序提供有关如何配置缓存和日志的详细信息。

 

               

 

任务 2 –在缓存中存储/检索简单的数据

在本任务中,您将向项目添加一个 web 窗体,添加代码来在缓存中存储和检索数据。

1.            在 Solution Explorer 中双击 Default.aspx 文件,在 Source 视图中将其打开。移除页面中 <asp:Content> 标签内部的所有内容,并使用以下 XHTML 标记替代:

ASPX

<table>

<tr>

<td><label>Key:</label></td>

<td ><asp:TextBox runat="server" ID="keyTextbox" /></td>

</tr>

<tr>

<td><label>Value:</label></td>

<td><asp:TextBox runat="server" ID="valueTxtBox" /></td>

</tr>

<tr>

<td colspan="2">

<asp:Button runat="server" id="addButton" Text="Add"/>

<asp:Button runat=server id="putButton" Text="Put"/>

<asp:Button runat=server id="getButton" Text="Get"/>

</td>

</tr>

<tr>

<td colspan="2">

<asp:Label runat="server" id="statusLabel"/>

</td>

</tr>

</table>

 

2.            切换到“Design”模式。您的 web 窗体应该看起来如下所示:

 

图 16

Design 模式中的 Web 窗体

 

3.            邮件单击设计器并选择 View Code,打开 Default.aspx.vb (Visual Basic) 或 Default.aspx.cs (C#) 文件。

4.            将以下语句添加到顶部:

C#

using Microsoft.Data.Caching;

 

Visual Basic

Imports Microsoft.Data.Caching

 

5.            有必要在 Session 中存储缓存对象,并在每次出现页面事件时检索该对象的相同实例。将该代码插入到页面类中,以将以下方法添加到页面:

(代码片段–   Velocity 简介实验 - 练习 2 GetCurrentCache – C#)

C#

private DataCache GetCurrentCache()

{

DataCache dCache;

if (Session["dCache"] != null)

    {

dCache = (DataCache)Session["dCache"];

    }

else

    {

var factory = new DataCacheFactory();

dCache = factory.GetCache("default");

Session["dCache"] = dCache;

    }

 

return dCache;

}

 

(代码片段–   Velocity 简介实验 - 练习 2 GetCurrentCache – VB)

Visual Basic

Private Function GetCurrentCache() As DataCache

Dim dCache As DataCache

 

If Not Session("dCache") Is Nothing Then

dCache = Session("dCache")

                  Else

Dim factory As New DataCacheFactory

dCache = factory.GetCache("default")

Session("dCache") = dCache

End If

 

Return dCache

End Function

 

注意:该方法查看 Session 对象,了解是否存在标记为“dCache”的对象。如果存在,将从 Session 中拉出该对象并返回。如果不存在,则创建一个新的缓存对象并存储在 Session 中。注意,Cache 对象不会直接实例化——使用工厂对象来创建 Cache 对象。在需要访问缓存时,事件将在页面上调用该方法。

 

6.            返回到设计视图并双击 AddButton 以创建一个用于按钮单击事件的处理程序。将以下代码添加到 AddButton_Click。该代码向缓存添加一个新键/值对。缓存的 Add 方法假设缓存中当前不存在该键。

(代码片段– Velocity 简介实验 - Ex2 AddButton_Click – C#)

C#

var dCache = GetCurrentCache();

 

var key = keyTextbox.Text;

var val = valueTxtBox.Text;

 

if (key == "" || val == "") return;

 

try

{

dCache.Add(key, val);

statusLabel.Text =

string.Format("Successfully added key {0} to cache.", key);

}

catch (Exception ex)

{

statusLabel.Text =

string.Format("Error adding key {0} to cache: {1}",

key, ex.Message);

}

 

(代码片段 – Velocity 简介实验 - 练习 2 AddButton_Click – VB)

Visual Basic

Dim dCache = GetCurrentCache()

 

Dim key = keyTextbox.Text

Dim val = valueTxtBox.Text

 

If key Is "" OrElse val Is "" Then

Return

End If

 

Try

dCache.Add(key, val)

statusLabel.Text = String.Format("Successfully added key {0} to cache.",

key)

Catch ex As Exception

statusLabel.Text = String.Format("Error adding key {0} to cache: {1}",

key, ex.Message)

End Try

 

7.            返回到设计视图并双击PutButton以创建一个用于按钮单击事件的处理程序。将以下代码添加到 PutButton_Click。该代码向缓存添加或更新一个新键/值对。缓存的 Put  方法检查该键是否已经存在于缓存中。如果该键不存在,则添加一个;如果该键存在,则更新该键的值。

(代码片段– Velocity 简介实验–练习 2  PutButton_Click – C#)

C#

var dCache = GetCurrentCache();

 

var key = keyTextbox.Text;

var val = valueTxtBox.Text;

 

if (key == "" || val == "") return;

 

try

{

dCache.Put(key, val);

statusLabel.Text =

string.Format("Successfully put key {0} to cache", key);

}

catch (Exception ex)

{

statusLabel.Text =

string.Format("Error putting key {0} to cache: {1}",

key, ex.Message);

}

 

(代码片段 – Velocity 简介实验 - 练习 2 PutButton_Click – VB)

Visual Basic

Dim dCache = GetCurrentCache()

 

Dim key = keyTextbox.Text

Dim val = valueTxtBox.Text

 

If key Is "" OrElse val Is "" Then

                Return

End If

 

Try

                dCache.Put(key, val)

                statusLabel.Text = String.Format("Successfully put key {0} to cache",

key)

Catch ex As Exception

                statusLabel.Text = String.Format("Error putting key {0} to cache: {1}",

key, ex.Message)

End Try

 

8.            返回到设计视图并双击GetButton以创建一个用于按钮单击事件的处理程序。将以下代码添加到 GetButton_Click。如果该键存在于缓存中,则 Get 方法检索相应的值;如果缓存中不存在该键,则 Get 方法返回 null。

(代码片段– Velocity 简介实验–练习 2  GetButton_Click – C#)

C#

var dCache = GetCurrentCache();

var key = keyTextbox.Text;

 

if (key == "") return;

 

try

{

var val = dCache.Get(key).ToString();

valueTxtBox.Text = val;

statusLabel.Text =

string.Format("Successfully did Get of key {0} from cache", key);

}

catch (Exception ex)

{

statusLabel.Text =

string.Format("Error getting key {0} from cache: {1}",

key, ex.Message);               

}

 

(代码片段 – Velocity 简介实验 - 练习 2 GetButton_Click – VB)

Visual Basic

Dim dCache = GetCurrentCache()

Dim key = keyTextbox.Text

 

If key Is "" Then

                Return

End If

 

Try

                Dim val = dCache.Get(key).ToString()

                valueTxtBox.Text = val

                statusLabel.Text = String.Format("Successfully did Get of key {0} from cache", key)

Catch ex As Exception

                statusLabel.Text = String.Format("Error getting key {0} from cache:{1}", key, ex.Message)

End Try

 

a.            保存所有文件并选择 Build | Build DemoVelocity1 编译项目

9.            按 F5 以调试模式运行应用程序。测试不同的输入。在按钮单击事件中设置断点,以在实际运行中查看代码情况。对于要测试的特定操作,查看本练习的验证 1 部分。

               

 

任务 3 –在缓存中存储/检索复杂的数据

在本任务中,您将向项目添加一个 web 窗体,添加代码从缓存存储和检索可序列化对象。

注意: 为了简便起见,我们不验证向所创建窗体的输入操作。用户必须小心地在每个窗体控件中输入合适的数据类型。例如,Employee ID 必须是整数,Hire Date 必须是有效日期。为生产环境编写的代码应该始终验证用户输入。

 

1.            向项目中添加一个新类。选择 Project | Add Class。将类名称更改为“Employee”,然后单击 Add 按钮。该类将添加到您的项目中并在类编辑器中打开。

2.            使用以下代码替换类定义。

(代码片段– Velocity 简介实验 - 练习 2 Employee 实体– C#)

C#

[Serializable]

public class Employee

{

public string FirstName { get; set; }

public string LastName { get; set; }

public string Address { get; set; }

public DateTime HireDate { get; set; }

public int EmployeeID { get; set; }

}

 

(代码片段– Velocity 简介实验 - 练习 2 Employee 实体– VB)

Visual Basic

<Serializable()>

Public Class Employee

                Public Property FirstName() As String

                Public Property LastName() As String

                Public Property Address() As String

                Public Property HireDate() As DateTime

                Public Property EmployeeID() As Integer

End Class

 

注意:该类标记为 Serializable。对象必须序列化之后才能添加到缓存。该类的范围增加为 public,允许类之外的代码访问。

 

3.            向项目中添加一个新的 web 窗体。选择 Project | Add New Item…。出现 Add New Item 对话框选择 Web Form using Master Page 模板,接受默认名称“WebForm1.aspx”,然后选择 Site.Master 主页面,单击 OK 按钮将 Web 窗体添加到项目中。web 窗体以设计模式出现在项目中。

4.            验证 WebForm1.aspx 文件是否在“Source”视图中打开。将以下粗体 XHTML 标记添加到 <asp:Content> 标记和 ContentPlaceHolderID MainContent 之间:

ASPX

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<table>

<tr>

<td>Employee ID</td>

<td>

<asp:TextBox ID="EmployeeIDTextbox" runat="server" />

</td>

</tr>

<tr>

<td>First Name</td>

<td>

<asp:TextBox ID="FirstNameTextbox" runat="server" />

</td>

</tr>

<tr>

<td>Last Name</td>

<td>

<asp:TextBox ID="LastNameTextbox" runat="server" />

</td>

</tr>

<tr>

<td>Address</td>

<td>

<asp:TextBox ID="AddressTextbox" runat="server" />

</td>

</tr>

<tr>

<td>Hire Date</td>

<td>

<asp:TextBox ID="HireDateTextbox" runat="server" />

</td>

</tr>

</table>

<table>

<tr>

<td>

<asp:Button runat="server" ID="AddButton" Text="Add"/>

</td>

<td>

<asp:Button runat="server" ID="PutButton" Text="Put"/>

</td>

<td>

<asp:Button runat="server" ID="GetButton" Text="Get"/>

</td>

</tr>

</table>

<asp:Label runat="server" ID="StatusLabel" Text="Ready" />

</asp:Content>

 

5.            切换到“Design”模式。您的 web 窗体应该看起来如下所示:

 

图 17

Design 模式中的 Web 窗体

 

6.            单击设计器界面然后选择 View Code,将以下语句添加到代码文件顶部:

C#

using Microsoft.Data.Caching;

 

Visual Basic

Imports Microsoft.Data.Caching

 

7.            有必要在 Session 中存储缓存对象,并在每次出现页面事件时检索该对象的相同实例。将该代码插入到页面类中,以将以下方法添加到页面:

(代码片段– Velocity 简介实验 - 练习 2 GetCurrentCache 2 - C#)

C#

private DataCache GetCurrentCache()

{

DataCache dCache;

if (Session["dCache"] != null)

    {

dCache = (DataCache)Session["dCache"];

    }

else

    {

var factory = new DataCacheFactory();

dCache = factory.GetCache("default");

Session["dCache"] = dCache;

    }

 

return dCache;

}

 

(代码片段– Velocity 简介实验 - 练习 2 GetCurrentCache 2 - VB)

Visual Basic

Private Function GetCurrentCache() As DataCache

Dim dCache As DataCache

If Session("dCache") IsNot Nothing Then

dCache = CType(Session("dCache"), DataCache)

Else

Dim factory = New DataCacheFactory()

dCache = factory.GetCache("default")

Session("dCache") = dCache

End If

 

Return dCache

End Function

 

8.            返回到设计视图并双击 AddButton 以创建一个用于按钮单击事件的处理程序。将以下代码添加到 AddButton_Click。该代码向缓存添加一个新键/值对。缓存的 Add 方法假设缓存中当前不存在键(注意,我们使用对象的初始化程序功能取代 Employee 对象的构造函数)。

(代码片段– Velocity 简介实验 - 练习 2 AddButton_Click 2 – C#)

C#

var dCache = GetCurrentCache();

var employeeID = Convert.ToInt32(EmployeeIDTextbox.Text);

var firstName = FirstNameTextbox.Text;

var lastName = LastNameTextbox.Text;

var address = AddressTextbox.Text;

var hireDate = Convert.ToDateTime(HireDateTextbox.Text);

 

var emp = new Employee

{

EmployeeID = employeeID,

FirstName = firstName,

LastName = lastName,

Address = address,

HireDate = hireDate

};

 

try

{

dCache.Add(employeeID.ToString(), emp);

StatusLabel.Text =

string.Format("Successfully added employee {0} to cache",

employeeID);

}

catch (Exception ex)

{

StatusLabel.Text =

string.Format("Error adding employee {0} to cache: {1}",

employeeID, ex.Message);

}

 

(代码片段 – Velocity 简介实验 - 练习 2 AddButton_Click 2 – VB)

Visual Basic

Dim dCache = GetCurrentCache()

Dim employeeID = Convert.ToInt32(EmployeeIDTextbox.Text)

Dim firstName = FirstNameTextbox.Text

Dim lastName = LastNameTextbox.Text

Dim address = AddressTextbox.Text

Dim hireDate = Convert.ToDateTime(HireDateTextbox.Text)

 

Dim emp = New Employee With {

.EmployeeID = employeeID,

.FirstName = firstName,

.LastName = lastName,

.Address = address,

.HireDate = hireDate

}

 

Try

dCache.Add(employeeID.ToString(), emp)

StatusLabel.Text = String.Format("Successfully added employee {0} to cache", employeeID)

Catch ex As Exception

StatusLabel.Text = String.Format("Error adding employee {0} to cache:{1}", employeeID, ex.Message)

End Try

 

9.            返回到设计视图并双击PutButton以创建一个用于按钮单击事件的处理程序。将以下代码添加到 PutButton_Click。该代码向缓存添加或更新一个新键/值对。缓存的 Put  方法检查该键是否已经存在于缓存中。如果该键不存在,则添加一个;如果该键存在,则更新该键的值。

(代码片段– Velocity 简介实验 - 练习 2 PutButton_Click 2 – C#)

C#

var dCache = GetCurrentCache();

var employeeID = Convert.ToInt32(EmployeeIDTextbox.Text);

var firstName = FirstNameTextbox.Text;

var lastName = LastNameTextbox.Text;

var address = AddressTextbox.Text;

var hireDate = Convert.ToDateTime(HireDateTextbox.Text);

 

var emp = new Employee

{

EmployeeID = employeeID,

FirstName = firstName,

LastName = lastName,

Address = address,

HireDate = hireDate

};

 

try

{

dCache.Put(employeeID.ToString(), emp);

StatusLabel.Text =

string.Format("Successfully added employee {0} to cache", employeeID);

}

catch (Exception ex)

{

StatusLabel.Text =

string.Format("Error putting employee {0} to cache:{1}", employeeID, ex.Message);

}

 

(代码片段 – Velocity 简介实验 - 练习 2 PutButton_Click 2 – VB)

Visual Basic

Dim dCache = GetCurrentCache()

Dim employeeID = Convert.ToInt32(EmployeeIDTextbox.Text)

Dim firstName = FirstNameTextbox.Text

Dim lastName = LastNameTextbox.Text

Dim address = AddressTextbox.Text

Dim hireDate = Convert.ToDateTime(HireDateTextbox.Text)

 

Dim emp = New Employee With {

.EmployeeID = employeeID,

.FirstName = firstName,

.LastName = lastName,

.Address = address,

.HireDate = hireDate

}

 

Try

dCache.Put(employeeID.ToString(), emp)

StatusLabel.Text = String.Format("Successfully added employee {0} to cache", employeeID)

Catch ex As Exception

StatusLabel.Text = String.Format("Error putting employee {0} to cache:{1}", employeeID, ex.Message)

End Try

 

10.          返回到设计视图并双击GetButton以创建一个用于按钮单击事件的处理程序。将以下代码添加到 GetButton_Click。如果该键存在于缓存中,则 Get 方法检索相应的值;如果缓存中不存在该键,则 Get 方法返回 null。

注意,对象必须强制转换为 Employee 类型才能使用。这是因为从缓存返回的值总是 System.Object 类型。

(代码片段– Velocity 简介实验 - 练习 2 GetButton_Click 2 – C#)

C#

var dCache = GetCurrentCache();

 

try

{

var emp = (Employee) dCache.Get(EmployeeIDTextbox.Text);

FirstNameTextbox.Text = emp.FirstName;

LastNameTextbox.Text = emp.LastName;

AddressTextbox.Text = emp.Address;

HireDateTextbox.Text = emp.HireDate.ToString();

 

StatusLabel.Text =

string.Format("Successfully did Get of employee {0} from cache", emp.EmployeeID);

}

catch (Exception ex)

{

StatusLabel.Text =

string.Format("Error getting employee {0} and {1}",

EmployeeIDTextbox.Text, ex.Message);

}

 

(代码片段 – Velocity 简介实验 - 练习 2 GetButton_Click 2 – VB)

Visual Basic

Dim dCache = GetCurrentCache()

 

Try

                Dim emp = CType(dCache.Get(EmployeeIDTextbox.Text), Employee)

                FirstNameTextbox.Text = emp.FirstName

                LastNameTextbox.Text = emp.LastName

                AddressTextbox.Text = emp.Address

                HireDateTextbox.Text = emp.HireDate.ToString()

 

                StatusLabel.Text = String.Format("Successfully did Get of employee {0} from cache", emp.EmployeeID)

Catch ex As Exception

                StatusLabel.Text = String.Format("Error getting employee {0} and {1}", EmployeeIDTextbox.Text, ex.Message)

End Try

 

11.          将启动页面更改为 WebForm1

a.            在 Solution Explorer 中,右键单击 WebForm1.aspx 并从弹出菜单中选择“Set As Start Page”

12.          保存所有文件并选择 Build | Build DemoVelocity1 编译项目

13.          按 F5 以调试模式运行应用程序。测试不同的输入。在按钮单击事件中设置断点,以在实际运行中查看代码情况。对于要测试的特定操作,查看本练习的验证 2 部分。

               

下一步:

练习 2:验证

               

练习 2:验证

要验证是否正确执行了所有练习的步骤,执行以下步骤:

注意:在运行该验证之前,请确保缓存群集能正常运行。为此,执行练习 1:安装和运行 Velocity 的任务 3 –启动 Velocity 群集中的描述的步骤。

 

验证 1:运行项目并测试缓存简单的数据

在本验证中,您将运行项目,向 Default.aspx 输入数据并测试为了添加、更新以及从缓存获取数据而编写的代码。

1.            在 Solution Explorer 中,右键单击 Default.aspx 并从弹出菜单中选择“Set As Start Page”

2.            按 F5 运行应用程序。应该出现 Default.aspx,其中应该包含您添加的文本框和按钮。

 

图 18

默认页面

 

3.            将一个值添加到缓存。

a.            在 Key 文本框中输入“Item1”。

b.            在 Value 文本框中输入“This is Item1”。

c.             单击 Add 按钮。

d.            按钮下的标签应该显示文本“Successfully added key Item1 to cache”。

e.            在 Key 文本框中输入“Item2”。

f.             在 Value 文本框中输入“This is Item2”。

g.            单击 Add 按钮。

h.            按钮下的标签应该显示文本“Successfully added key Item2 to cache”。

4.            尝试将一个重复键添加到缓存中。

a.            在 Key 文本框中输入“Item1”。

b.            在 Value 文本框中输入“This is the new value for Item1”。

c.             单击 Add 按钮。

d.            按钮下的标签应该显示一条错误消息。

5.            使用 Put 方法在缓存中更新项目。

a.            在 Key 文本框中输入“Item1”。

b.            在 Value 文本框中输入“This is the new value for Item1”。

c.             单击 Put 按钮。

d.            按钮下的标签应该显示文本“Successfully put key Item1 to cache”。

6.            从缓存获取一项。

a.            在 Key 文本框中输入“Item2”。

b.            删除 Value 文本框中的所有文本。

c.             单击 Get 按钮。

d.            按钮下的标签应该显示文本“Successfully did Get of key Item1 to cache”。

7.            尝试获取缓存中没有的项。

a.            在 Key 文本框中输入“Item5”。

b.            删除 Value 文本框中的所有文本。

c.             单击 Get 按钮。

d.            按钮下的标签应该显示一条错误消息。

               

验证 2:运行项目并测试缓存复杂的数据

在本验证中,您将运行项目,向 Form2 输入数据并测试为了添加、更新以及从缓存获取数据而编写的代码。

1.            在 Solution Explorer 中,右键单击 WebForm1.aspx 并从弹出菜单中选择“Set As Start Page”。

2.            按 F5 运行应用程序。应该出现 WebForm1,其中应该包含您添加的文本框和按钮。

 

图 19

次级页面

 

3.            将一个值添加到缓存。

a.            在 Employee ID 文本框中输入“1”。

b.            在 First Name 文本框中输入“George”。

c.             在 Last Name 文本框中输入“Bush”。

d.            在 Address 文本框中输入“Kennebunkport, ME”。

e.            在 Hire Date 文本框中输入“1/20/1989”。

f.             单击 Add 按钮。

g.            按钮下的标签应该显示文本“Successfully added key 1 to cache”。

h.            在 Employee ID 文本框中输入“2”。

i.              在 First Name 文本框中输入“Bill”。

j.             在 Last Name 文本框中输入“Clinton”。

k.            在 Address 文本框中输入“Hope, AR”。

l.              在 Hire Date 文本框中输入“1/20/1993”。

m.           单击 Add 按钮。

n.            按钮下的标签应该显示文本“Successfully added key 2 to cache”。

4.            尝试将一个重复键添加到缓存中。

a.            在 Employee ID 文本框中输入“1”。

b.            在 First Name 文本框中输入“Jimmy”。

c.             在 Last Name 文本框中输入“Carter”。

d.            在 Address 文本框中输入“Plains, GA”。

e.            在 Hire Date 文本框中输入“1/19/1977”。

f.             单击 Add 按钮。

g.            按钮下方的标签应该显示一条错误消息,因为键“1”已经存在于缓存中。

5.            使用 Put 方法在缓存中更新项目。

a.            在 Employee ID 文本框中输入“1”。

b.            在 First Name 文本框中输入“Ronald”。

c.             在 Last Name 文本框中输入“Reagan”。

d.            在 Address 文本框中输入“1600 Pennsylvania”。

e.            在 Hire Date 文本框中输入“2/6/1981”。

f.             单击 Put 按钮。

g.            按钮下的标签应该显示文本“Successfully put key Item1 to cache”。

6.            从缓存获取一项

a.            在 Employee ID 文本框中输入“2”。

b.            删除窗体上其他文本框中的所有文本。

c.             单击 Get 按钮。

d.            按钮下的标签应该显示文本“Successfully did Get of key 2 from cache”。 

e.            文本框应该显示关于员工 2 的信息(如果按照上述步骤进行的话应该是 Bill Clinton)。

7.            尝试获取缓存中没有的项。

a.            在 Employee ID 文本框中输入“5”。

b.            删除窗体上其他文本框中的所有文本。

c.             单击 Get 按钮。

d.            按钮下的标签应该显示一条错误消息。

               

下一步:

练习 3:在 ASP.NET 中使用 Velocity 的 SessionState 提供程序

               

 

练习 3:在 ASP.NET 中使用 Velocity 的 SessionState 提供程序

本练习展示如何挂钩 ASP.NET 以使用外部 Velocity SessionState 提供程序。这将得到“两全其美”的结果:一方面支持流程外的会话处理,另一方面又不会影响基于 SQL 的会话管理性能。

注意:要验证每个步骤是否正确执行,建议在每次任务结束时构建解决方案。

 

注意:对于本实验,您应该以管理员权限运行 Visual Studio 2010。这样您才能调试代码和访问必需的配置文件。

 

任务 1 –在 Visual Studio 中创建一个网站

在本任务中,您将创建一个 web 应用程序,让缓存 API 可用于该应用程序。

1.            打开 Microsoft Visual Studio 2010,选择 Start | All Programs | Microsoft Visual Studio 2010,右键单击 Microsoft Visual Studio 2010 并选择 Run as administrator。

2.            选择 File | New | New Project...出现 New Project 对话框。

 

图 20

New Project 对话框

 

a.            在 Project Types 中选择 Visual Basic 或 Visual C#。

b.            在 Templates 下,选择 ASP.NET Web Application

c.             将网站命名为“DemoVelocity2”

3.            添加对缓存库的引用

a.       在 Visual Studio 中打开 DemoVelocity2 项目,选择 Project | Add Reference…,将出现 Add References 对话框。 

b.            选择 Browse 选项卡。

 

图 21

Add Reference 对话框

 

c.             打开 C:\Program Files\Microsoft Distributed Cache\V1.0 文件夹并选择 CacheBaseLibrary.dll 和 ClientLibrary.dll。单击 OK 按钮添加对这些库的引

用。

4.            修改 web.config 文件以支持缓存

a.            添加以下声明:

XML

<configSections>

<section name="dataCacheClient" type="Microsoft.Data.Caching.DataCacheClientSection, CacheBaseLibrary" allowLocation="true" allowDefinition="Everywhere"/>

</configSections>

 

b.            将以下代码添加到“configSections”组之后的“configuration”部分:

XML

<dataCacheClient deployment="simple">

<localCache isEnabled="true" sync="TTLBased" ttlValue="300" />

<hosts>

<!--List of services -->

<host name="localhost" cachePort="22233" cacheHostName="DistributedCacheService"/>

</hosts>

</dataCacheClient>

 

c.             将以下代码添加到“system.web”部分。该部分告知 web 应用程序使用 Velocity 提供程序处理所有 SessionState 请求。

XML

<sessionState mode="Custom" customProvider="Velocity">

<providers>

<add name="Velocity" type="Microsoft.Data.Caching.DataCacheSessionStoreProvider, ClientLibrary" />

</providers>

</sessionState>

 

 

5.            添加代码,在一个页面上将数据存储到会话中。

a.            在 Solution Explorer 中双击 Default.aspx 文件,在 Source 视图中将其打开。移除页面中 <asp:Content> 标签内部的所有内容,并使用以下 XHTML 标记替代:

ASPX

<table>

<tr>

<td><label>Enter your Name:</label></td>

<td ><asp:TextBox runat="server" ID="NameTextbox" /></td>

</tr>

<tr>

<td>

<asp:Button runat="server" id="SaveNameButton" Text="Save Name"

onclick="SaveNameButton_Click"/>

</td>

</tr>

</table>

 

b.            切换到“Design”模式。您的 web 窗体应该看起来如下所示:

 

图 22

Design 模式中的 Web 窗体

 

c.             双击“SaveName”按钮打开代码编辑器。将以下代码添加到 SaveNameButton_Click 方法。这将用户输入的名称保存到会话对象中。

(代码片段– Velocity 简介实验 - 练习 3 SaveNameButton_Click – C#)

C#

if (NameTextbox.Text == "") return;

Session["YourName"] = NameTextbox.Text;

Response.Redirect("WebForm1.aspx");

 

(代码片段– Velocity 简介实验 - 练习 3 SaveNameButton_Click – VB)

Visual Basic

If NameTextBox.Text = "" Then

Return

End If

Session("YourName") = NameTextBox.Text

Response.Redirect("WebForm1.aspx")

 

6.            添加逻辑,从会话中检索数据

a.            向网站添加一个新页面。选择 Project | Add New Item…。出现 Add New Item 对话框

b.            从 Templates 列表中选择 Windows Web Form using Master Page。

c.             保留默认名称“WebForm1.aspx”

d.            单击 Add 按钮并选择 Site.Master 主页。Visual Studio 向网站添加了一个新页面 WebForm1.aspx,并在编辑器中打开该页面。单击编辑器的 Design 选项卡查看设计界面。

e.            将一个标签从 Toolbox 中拖动到 WebForm1.aspx 的设计界面上。将其 ID 设置为“GreetingLabel”,将其 Text 属性设置为“Unknown User”。

 

图 23

WebForm1 页面设计

 

f.             双击 WebForm1.aspx 设计界面的空白部分打开该窗体的代码窗口。在 Page_Load 方法中输入以下代码。这将从会话对象中检索值并显示在页面上。

(代码片段– Velocity 简介实验 - 练习 3 Page_Load – C#)

C#

if (Session["YourName"] == null)

{

GreetingLabel.Text = "Unknown User";

}

else

{

GreetingLabel.Text = "Hello " + Session["YourName"].ToString();

}

 

(代码片段 – Velocity 简介实验 - 练习 3 Page_Load – VB)

Visual Basic

If Session("YourName") Is Nothing Then

GreetingLabel.Text = "Unknown User"

Else

GreetingLabel.Text = "Hello " & Session("YourName").ToString()

End If

 

g.            保存所有文件并编译网站。

               

下一步:

练习 3:验证

               

练习 3:验证

要验证是否正确执行了所有练习的步骤,执行以下步骤:

注意:在运行该验证之前,请确保缓存群集能正常运行。为此,执行练习 1:安装和运行 Velocity 的任务 5 –启动 Velocity 群集中的描述的步骤。

 

1.            按 F5 运行网站。

2.            导航到页面 default.aspx 并输入您的名字。 

3.            导航到页面 WebForm1.aspx。从会话/缓存中检索之后,系统将显示您的名字。

               

下一步:

练习 4(可选):在群集中配置 Velocity 缓存

               

 

练习 4(可选):在群集中配置 Velocity 缓存

Velocity 在缓存分布在多台机器上时最为有效。这可以增加应用程序的可伸缩性。在本练习中,我们将在多台机器上安装 Velocity 并配置缓存以使用每台机器。如果处于实验室环境中,您可能无法完成该练习。

 

任务 1 –在第二台 PC 上安装 Velocity

在本任务中,我们将在第二台 PC 或虚拟 PC 上安装 Velocity。

1.            移动到第二台 PC 或虚拟 PC,这台 PC 必须与您执行上一个练习时使用的 PC 位于同一个域或工作组。如本实验的练习 1 所述,在此 PC 上安装 Velocity。

2.            在 Cache Host Configuration 屏幕上,确保指定的 Cluster Name (“Cluster1”) 与在第一台 PC 上安装 Velocity 时使用的相同。

 

图 24

Cache Host Configuration

               

 

任务 2 –配置 Velocity 以使用 Multiple PC

为了让每个 Velocity 服务感知到群集中的其他机器,您必须修改 ClusterConfig.xml。该文件位于 Cluster Configuration Share 下的“Cluster1”目录中。在本实验中,它将位于 c:\VelocityLab 目录中。

1.            在安装了 Velocity 的两台 PC 上使用记事本打开 c:\VelocityLab ClusterConfig.xml。该 XML 文件的 <hosts> 部分应该列出了一个主机。例如:

XML

<hosts>

<host name="PC1" hostId="1616225007" quorumHost="True"

cacheHostName="DistributedCacheService" cachePort="22233"

clusterPort="22234" size="2048" lowWaterMark="70"

highWaterMark="90" />

</hosts>

 

2.            向每个文件添加第二个 <host> 元素,指定将属于群集的另一台 PC 的名称。

注意: 最简单的实现方式是从另一台 PC 的 ClusterConfig.xml 文件中复制 <host> 元素。 

 

完成之后,<hosts> 部分应该类似如下 XML。

XML

<hosts>

<host name="PC1" hostId="1616225007" quorumHost="True"

cacheHostName="DistributedCacheService" cachePort="22233"

clusterPort="22234" size="2048" lowWaterMark="70"

highWaterMark="90" />

<host name="PC2" hostId="1616225008" quorumHost="True"

cacheHostName="DistributedCacheService" cachePort="22233"

clusterPort="22234" size="2048" lowWaterMark="70"

highWaterMark="90" />

</hosts>

 

注意:群集中的主机需要通过远程访问彼此通信,因此必须提供有效凭据才能执行一些操作,比如访问共享配置存储器,访问和启动/停止远程主机的服务等。如果使用对所有主机具有管理员权限的域账户安装 Velocity,这些访问权限都将很容易配置。

有关更多信息,请参见 http://social.msdn.microsoft.com/forums/en-US/velocity/thread/402b9465-f157-42a8-9a08-9e1a47a66783/

 

3.            将“PC1”和“PC2”替换为每台 PC 的机器名。

               

下一步:

总结

               

 

 

总结

在本实验中,您安装并使用 Microsoft Distributed Caching Service (“Velocity”) 来缓存资源和加速对数据检索的访问。

您通过 API 访问缓存,并配置了一个网站,使用 Velocity 存储其会话状态。您还实验了各种类型的缓存配置。