代码中实际运用memcached——mycode
1、下载安装号memcached.exe
2、下载memcacheddotnet_clientlib,并将Commons.dll、ICSharpCode.SharpZipLib.dll、log4net.dll、Memcached.ClientLibrary.dll几个文件引用到项目中;
3、完成配置文件,在<configuration>节点下添加节点<configSections>,在<configSection>外添加log4net配置,完整如下:
<configuration>
<!--<appSettings>
<add key="ServerIP" value="127.0.0.1"/>
<add key="ServerPort" value="11011"/>
</appSettings>-->
<!--<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>-->
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="LogFiles/"/>
<param name="AppendToFile" value="true"/>
<param name="MaxSizeRollBackups" value="10"/>
<param name="StaticLogFileName" value="false"/>
<param name="DatePattern" value="yyyy-MM-dd".txt""/>
<param name="RollingStyle" value="Date"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger %ndc - %message%newline"/>
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger %ndc - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
<appender-ref ref="ConsoleAppender" />
</root>
<logger name="Memcached.ClientLibrary">
<level value="WARN" />
</logger>
</log4net>
</configuration>
4、实现代码:
using Memcached.ClientLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Memcached
{
public static class MemcachedHelper
{
private static MemcachedClient mc;
static MemcachedHelper()
{
try
{
string[] serverList = new string[] { "127.0.0.1:11211" };
SockIOPool sock = SockIOPool.GetInstance();
sock.SetServers(serverList);//添加服务器列表
sock.InitConnections = 3;//设置连接池初始数目
sock.MinConnections = 3;//设置最小连接数目
sock.MaxConnections = 5;//设置最大连接数目
sock.SocketConnectTimeout = 1000;//设置连接的套接字超时。
sock.SocketTimeout = 3000;//设置套接字超时读取
sock.MaintenanceSleep = 30;//设置维护线程运行的睡眠时间。如果设置为0,那么维护线程将不会启动;
sock.Failover = true; //如果为false,对所有创建的套接字关闭Nagle的算法。
sock.Nagle = false;
sock.Initialize();
mc = new MemcachedClient();
}
catch (Exception ex)
{
var exception = ex.Message + ex.StackTrace;
}
}
public static bool SetValue(string key, object value, DateTime expiry)
{
bool isSuccess=false;
try
{
isSuccess = mc.Set(key, value, expiry);
}
catch (Exception ex)
{
var excepion = ex.Message + ex.StackTrace;
}
return isSuccess;
}
public static object GetValue(string key)
{
var result = mc.Get(key);
return result;
}
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。