C#链接阿里云OCS
一、阿里云OCS简单介绍
阿里云OCS兼容Memcached,因为OCS就相当于Memcached的服务器端,我们代码只是当作客户端,链接上服务器端就行了。阿里云OCS介绍详情见 http://www.aliyun.com/product/ocs?spm=5176.2020520107.0.0.s2zgFk#Help 。
二、C#客户端链接OCS
1.阿里云文档上介绍的是用Enyim.Caching去链接OCS。那我们项目中就用nuget去下载Enyim.Caching包。nuget搜索Enyim,搜索到的结果如下图,第一个是nolog版本的,第二个是带log的,随便一个都可以。
nuget搜索结果如下:

2.安装成功以后,再链接OCS,写个初始化memcached的代码,代码如下。
using Enyim.Caching;
using Enyim.Caching.Configuration;
using Enyim.Caching.Memcached;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks; namespace OCS
{
public class MemCached
{
private static MemcachedClient MemClient; static readonly object padlock = new object();
//线程安全的单例模式
public static MemcachedClient getInstance(string hostName,string userName,string password)
{
if (MemClient == null)
{
lock (padlock)
{
if (MemClient == null)
{
MemClientInit(hostName,userName,password);
}
}
}
return MemClient;
} static void MemClientInit(string hostName,string userName,string password)
{
try
{
//初始化缓存
MemcachedClientConfiguration memConfig = new MemcachedClientConfiguration();
IPAddress newaddress = IPAddress.Parse(Dns.GetHostEntry(hostName).AddressList[].ToString());
IPEndPoint ipEndPoint = new IPEndPoint(newaddress, ); // 配置文件 - ip
memConfig.Servers.Add(ipEndPoint);
// 配置文件 - 协议
memConfig.Protocol = MemcachedProtocol.Binary;
// 配置文件-权限
memConfig.Authentication.Type = typeof(PlainTextAuthenticator);
memConfig.Authentication.Parameters["zone"] = "";
memConfig.Authentication.Parameters["userName"] = userName;
memConfig.Authentication.Parameters["password"] = password;
//下面请根据实例的最大连接数进行设置
memConfig.SocketPool.MinPoolSize = ;
memConfig.SocketPool.MaxPoolSize = ;
MemClient = new MemcachedClient(memConfig);
}
catch (Exception)
{
MemClient = null;
}
}
}
}
3.再写个服务去调用上面的初始化代码,创建MemcachedClient的实例去调用客户端代码。下面代码中的构造函数中的_setting.HostAddress, _setting.AccessId, _setting.AccessKey分别对应的是,OCS的链接地址,链接密码和OCS的实例ID。
using Enyim.Caching;
using Enyim.Caching.Memcached;
using Enyim.Caching.Memcached.Results;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using Zupo.Core.Caching;
using ServiceStack.Text;
using Newtonsoft.Json; namespace OCS
{
public class OCSService
{
IOCSSetting _setting; private MemcachedClient client; public OCSService(IOCSSetting setting)
{
this._setting = setting;
this.client = MemCached.getInstance(_setting.HostAddress, _setting.AccessId, _setting.AccessKey);
} /// <summary>
/// 是否链接上服务器
/// </summary>
protected bool LinkServer
{
get
{
return client == null ? false : true;
}
} protected IGetOperationResult ExecuteGet(string key)
{
return client.ExecuteGet(key);
} /// <summary>
/// 根据key获得缓存
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
protected object Get(string key)
{
return client.Get(key);
} /// <summary>
/// 根据key获得缓存 泛型方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
protected T Get<T>(string key)
{
try
{
//JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
//string objectStr = client.Get(key).ToString();
var obj = client.Get(key);
if (obj != null)
{
return JsonConvert.DeserializeObject<T>(obj.ToString());
}
return default(T);
//return objectStr.FromJson<T>();
}
catch (Exception)
{
this.Remove(key);
return default(T);
}
} /// <summary>
/// 根据key获得缓存 泛型方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
protected List<T> GetList<T>(string key)
{
var objectStr = client.Get(key).ToString(); //return objectStr.FromJson<List<T>>();
return JsonConvert.DeserializeObject<List<T>>(objectStr);
} /// <summary>
/// 根据数组key获得数据 IDictionary
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
protected IDictionary<string, object> GetByKeys(string[] keys)
{
return client.Get(keys);
} /// <summary>
/// 该key值缓存是否存在
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool Contains(string key)
{
object value; return client.TryGet(key, out value);
} /// <summary>
/// 存储,有的话直接覆盖
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
protected bool Set(string key, object value)
{
return client.Store(StoreMode.Set, key, value);
} /// <summary>
/// 存储,有的话直接覆盖
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
protected bool Set<T>(string key, T value)
{
try
{
//执行序列化
//string objectStr = value.ToJson();
string objectStr = JsonConvert.SerializeObject(value, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
return client.Store(StoreMode.Set, key, objectStr);
}
catch(Exception)
{
return false;
} } /// <summary>
/// 存储,有的话直接覆盖
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
protected bool Set<T>(string key, List<T> value)
{
//执行序列化
//string objectStr = value.ToJson();
string objectStr = JsonConvert.SerializeObject(value, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
return client.Store(StoreMode.Set, key, objectStr);
} /// <summary>
/// 存储,有的话直接覆盖
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expire">失效时间:TimeSpan</param>
/// <returns></returns>
protected bool SetExpires(string key, object value, TimeSpan expire)
{
try
{
//string objectStr = value.ToJson();
string objectStr = JsonConvert.SerializeObject(value, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
return client.Store(StoreMode.Set, key, objectStr, expire);
}
catch(Exception)
{
return false;
} } /// <summary>
/// 存储,有的话直接覆盖
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expire">失效时间:TimeSpan</param>
/// <returns></returns>
protected bool SetExpires<T>(string key, T value, TimeSpan expire)
{
//执行序列化
//string objectStr = value.ToJson();
string objectStr = JsonConvert.SerializeObject(value, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
return client.Store(StoreMode.Set, key, objectStr, expire);
} /// <summary>
/// 删除cached
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public void Remove(string key)
{
client.Remove(key);
} /// <summary>
/// Removes items by pattern
/// 该方法未实现
/// </summary>
/// <param name="pattern">pattern</param>
public virtual void RemoveByPattern(string pattern)
{
var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
//var keysToRemove = new List<String>(); //var allkeys = client.
//foreach (var key in allkeys)
// if (regex.IsMatch(key))
// keysToRemove.Add(key); //foreach (string key in keysToRemove)
//{
// Remove(key);
//}
} /// <summary>
/// 清空ocs缓存
/// </summary>
/// <returns></returns>
public void Clear()
{
client.FlushAll();
}
}
}
MemcachedClient
三、使用注意点
因为OCS只支持key/value的格式进行存储,所以我项目中先运用了Newtonsoft.Json去先对对象序列化,再存入到OCS上,读取的时候再反序列化读取。代码如下:
/// <summary>
/// 存储,有的话直接覆盖
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
protected bool Set<T>(string key, T value)
{
try
{
//执行序列化
string objectStr = JsonConvert.SerializeObject(value, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
return client.Store(StoreMode.Set, key, objectStr);
}
catch(Exception)
{
return false;
} }
代码中设置了JsonSerializerSettings,因为项目用的是EF,一些对象里面的属性可能是另外一个对象还有是一些死循环的属性,所以数据量会比较大,直接执行序列化会内存溢出的,所以要在对象里面不需要序列化的属性上加上[JsonIgnore],忽略此属性或字段序列化。
那么反序列化获取数据代码如下:
/// <summary>
/// 根据key获得缓存 泛型方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
protected T Get<T>(string key)
{
try
{
var obj = client.Get(key);
if (obj != null)
{
return JsonConvert.DeserializeObject<T>(obj.ToString());
}
return default(T);
}
catch (Exception)
{
this.Remove(key);
return default(T);
}
}
C#链接阿里云OCS的更多相关文章
- 【阿里云产品公测】在Laravel4框架中使用阿里云OCS缓存
作者:阿里云用户 supechina Laravel 是我最近用得非常多而且越用就越喜欢的一款PHP框架,由于没有向下兼容的历史包袱,完全面向对象的风格,借助 Facades 优雅的 IoC Cont ...
- 阿里云 OCS SDK for NodeJS介绍
阿里云 OCS SDK for NodeJS介绍 阿里云技术团队:熊亮 阿里云 SDK for NodeJS 是为 NodeJS 开发者提供使用阿里云各项服务的统一入口,由阿里云UED团队负责开发维护 ...
- 云计算之路-阿里云上:愚人节被阿里云OCS愚
今天是愚人节,而我们却被阿里云OCS愚,很多地方的缓存一直不过期,造成很多页面中的数据一直不更新.这篇博文将向您分享我们这两天遇到的OCS问题. 阿里云OCS(Open Cache Service)是 ...
- C#链接阿里云KVStore
KVStore的简单介绍 阿里云KVStore兼容Redis.因为KVStore就相当于Redis的服务器端,我们代码只是当作客户端,链接上服务器端就行了,阿里云的KVStore详情文档见,https ...
- 数据库工具链接阿里云MySQL数据库
数据库工具:Toad for MySQL ssh工具:XShell 5 跳板机配置: 配置通道: 源主机:数据库工具链接的地址: 侦听接口:数据库工具侦听接口: 目标主机:数据库阿里云地址: 目标端口 ...
- .Net程序测试使用阿里云OCS开放缓存服务
首先需要有一个阿里的OCS实例和ECS云服务器 请确认这两个是在同一个可用区的,这个很重要! 这两个可以在阿里云官网申请得到 拿到OCS之后 进入OCS控制台,点击下面的客户端下载选择.Net客 ...
- 使用Xshell链接阿里云服务
1.下载Xshell,进入xshell官网 https://xshell.en.softonic.com/,选择免费版本进行下载,在该页面https://www.netsarang.com/zh/fr ...
- navicat链接阿里云mysql报80070007: SSH Tunnel: Server does not support diffie-hellman-group1-sha1 for keyexchange
http://www.jianshu.com/p/200572ed066c navicat 链接数据库 使用navicat 的ssh通道连接数据库回遇到权限问题 错误代码如下: 80070007: ...
- 本机ubuntu链接阿里云服务器(也是ubuntu)
首先在本机安装ssh工具,并修改配置文件(参考:http://www.cnblogs.com/herd/p/5009067.html) 第一步:ssh 100.121.156.32(即:服务器的ip地 ...
随机推荐
- Sql Server之旅——第十三站 对锁的初步认识
终于这个系列快结束了,马上又要过年了,没什么心情写博客...作为一个开发人员,锁机制也是我们程序员必须掌握的东西,很久之前 在学习锁的时候,都是教科书上怎么说,然后我怎么背,缺少一个工具让我们眼见为实 ...
- Use Excel Pivot Table as a BI tool
Normally, we have created a table, view in database or cube in SSAS, user can use Excel as a BI tool ...
- 高效coder,筹备开源框架toutou.escort.js
背景:JavaScript在工作中运用的非常广泛,作为一门弱类型语言,在使用JavaScript的时候,很多事情需要coder manual的去完成,这无疑增加了coder的工作量. 扩展:在这样的背 ...
- Linux 学习001
遇到的问题一: xxx is not in the sudoers file.This incident will be reported.的解决方法 1.切换到root用户下,怎么切换就不用说了吧, ...
- Linux rpm 查询
[root@wang /]# rpm -qa // 查看安装所有包 [root@wang /]# rpm -qa |grep vim // 查询所安装的包 +包名 [root@wang /]# rpm ...
- linux挂载windows上的共享文件夹
假定win机d:/folder/share的共享名为 share , 有用户administrator ,密码123 在linux机上,把share挂到/mnt目录:mount -t cifs -o ...
- 《InsideUE4》-3-GamePlay架构(二)Level和World
UE4深入学习QQ群: 456247757 引言 上文谈到Actor和Component的关系,UE利用Actor的概念组成一片游戏对象森林,并利用Component组装扩展Actor的能力,让世界里 ...
- NOIP2013pj小朋友的数字[DP 最大子段和]
描述 有 n 个小朋友排成一列.每个小朋友手上都有一个数字,这个数字可正可负.规定每个小朋友的特征值等于排在他前面(包括他本人)的小朋友中连续若干个(最少有一个)小朋友手上的数字之和的最大值.作为这些 ...
- NOIP2015子串[序列DP]
题目背景 无 题目描述 有两个仅包含小写英文字母的字符串 A 和 B.现在要从字符串 A 中取出 k 个互不重 叠的非空子串,然后把这 k 个子串按照其在字符串 A 中出现的顺序依次连接起来得到一 个 ...
- android studio 应用小知识总结
1.在复制一个工程文件后 想修改包名,则在Android下的java中的 Android test中,鼠标右键Refactor->rename->Rename_package->Do ...