使用Azure Redis Cache

通过上一篇博客《Redis Cache 简介》我们已经简单了解了Azure Redis Cache,这里就不过多赘述了。

1、创建Redis Cache

创建Redis Cache之前,我们首先要登录到 Azure Portal上,点击 New, Data + Storage, Redis Cache。

使用Azure Redis Cache

这里有一点需要说明一下,由于国内Azure目前不支持New Portal,因此国内的Azure订阅只能通过Powershell创建Redis Cache

#弹出界面输入用户名密码
Login-AzureRmAccount
#获取当前订阅名称
Get-AzureRmSubscription| Sort SubscriptionName|Select SubscriptionName
#选择当前订阅
Select-AzureRmSubscription -SubscriptionName {SubscriptionName}
#在日本西部创建资源组
New-AzureRmResourceGroup -Name {ResourceGroupName} -Location "Japan West"
#在日本西部创建256MB的Redis Cache,服务级别为Basic
New-AzureRmRedisCache -ResourceGroupName {ResourceGroupName} -Name {RedisCacheName} -Location "Japan West" -Sku Basic -Size C0
#查看已经创建好的Redis Cache
Get-AzureRmRedisCache

 2、使用Redis Cache

创建一个Web Application,打开NuGet控制台输入:Install-Package StackExchange.Redis或者Install-Package StackExchange.Redis.StrongName,添加对程序集的引用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using StackExchange.Redis;
using System.Net; namespace AspNet5_Owin
{
public class RedisManager
{
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
ConfigurationOptions opt = new ConfigurationOptions
{
Ssl = true,
AbortOnConnectFail = false,
Password = "{Redis Cache Keys}"
};
opt.EndPoints.Add(new DnsEndPoint("{Host Name}", {Ssl Port}));
return ConnectionMultiplexer.Connect(opt);
}); public static ConnectionMultiplexer Connection
{
get
{
return lazyConnection.Value;
}
} private static IDatabase cache = Connection.GetDatabase(); public static void CacheSet(string key, string value)
{
cache.StringSet(key, value, TimeSpan.FromSeconds());
} public static string CacheGet(string key)
{
return cache.StringGet(key);
} }
}

将字符串添加到Redis Cache中并取回

//将字符串存储到Redis Cache中
RedisManager.CacheSet("name", "zhangsan");
//将字符串从Redis Cache中取回
string name = RedisManager.CacheGet("name");

将对象添加到Redis Cache中并取回

[Serializable]
class Employee
{
public int Id { get; set; }
public string Name { get; set; } public Employee(int EmployeeId, string Name)
{
this.Id = EmployeeId;
this.Name = Name;
}
}
RedisManager.CacheSet("employee", JsonConvert.SerializeObject(new Employee(, "Clayton Gragg")))
Employee employee = JsonConvert.DeserializeObject<Employee>(RedisManager.CacheGet("employee"))
上一篇:ABP中使用Redis Cache(2)


下一篇:浅谈自我对git的初步认识