defaultredis expiretimee="2000" 是多长时间

初次见游客,大熊猫幼仔抱着饲养员的腿不放。
一辆小轿车和路过的火车发生碰撞,事故致2死1伤。
声明:本文由入驻搜狐公众平台的作者撰写,除搜狐官方账号外,观点仅代表作者本人,不代表搜狐立场。
  接上文
  3.3、Redis配置参数,redis.properties:
  #redis中心
  #绑定的主机地址
  redis.host=127.0.0.1
  #指定Redis监听端口,默认端口为6379
  redis.port=6379
  #授权密码(本例子没有使用)
  redis.password=123456
  #最大空闲数:空闲链接数大于maxIdle时,将进行回收
  redis.maxIdle=100
  #最大连接数:能够同时建立的“最大链接个数”
  redis.maxActive=300
  #最大等待时间:单位ms
  redis.maxWait=1000
  #使用连接时,检测连接是否成功
  redis.testOnBorrow=true
  #当客户端闲置多长时间后关闭连接,如果指定为0,表示关闭该功能
  redis.timeout=10000
  3.4、添加接口及对应实现RedisTestService.Java和RedisTestServiceImpl.java:
  package com.luo.
  public interface RedisTestService {
  public String getTimestamp(String param);
  package com.luo.service.
  import org.springframework.stereotype.S
  import com.luo.service.RedisTestS
  @Service
  public class RedisTestServiceImpl implements RedisTestService {
  public String getTimestamp(String param) {
  Long timestamp = System.currentTimeMillis();
  return timestamp.toString();
  3.5、本例采用spring aop切面方式进行缓存,配置已在上面spring配置文件中,对应实现为MethodCacheInterceptor.java:
  package com.luo.redis.
  import java.io.S
  import java.util.concurrent.TimeU
  import org.aopalliance.intercept.MethodI
  import org.aopalliance.intercept.MethodI
  import org.springframework.data.redis.core.RedisT
  import org.springframework.data.redis.core.ValueO
  public class MethodCacheInterceptor implements MethodInterceptor {
  private RedisTemplate&Serializable, Object& redisT
  private Long defaultCacheExpireTime = 10l; // 缓存默认的过期时间,这里设置了10秒
  public Object invoke(MethodInvocation invocation) throws Throwable {
  Object value =
  String targetName = invocation.getThis().getClass().getName();
  String methodName = invocation.getMethod().getName();
  Object[] arguments = invocation.getArguments();
  String key = getCacheKey(targetName, methodName, arguments);
  // 判断是否有缓存
  if (exists(key)) {
  return getCache(key);
  // 写入缓存
  value = invocation.proceed();
  if (value != null) {
  final String tkey =
  final Object tvalue =
  new Thread(new Runnable() {
  public void run() {
  setCache(tkey, tvalue, defaultCacheExpireTime);
  }).start();
  } catch (Exception e) {
  e.printStackTrace();
  if (value == null) {
  return invocation.proceed();
  * 创建缓存key
  * @param targetName
  * @param methodName
  * @param arguments
  private String getCacheKey(String targetName, String methodName,
  Object[] arguments) {
  StringBuffer sbu = new StringBuffer();
  sbu.append(targetName).append(&_&).append(methodName);
  if ((arguments != null) && (arguments.length != 0)) {
  for (int i = 0; i & arguments. i++) {
  sbu.append(&_&).append(arguments[i]);
  return sbu.toString();
  * 判断缓存中是否有对应的value
  * @param key
  * @return
  public boolean exists(final String key) {
  return redisTemplate.hasKey(key);
  * 读取缓存
  * @param key
  * @return
  public Object getCache(final String key) {
  Object result =
  ValueOperations&Serializable, Object& operations = redisTemplate
  .opsForValue();
  result = operations.get(key);
  * 写入缓存
  * @param key
  * @param value
  * @return
  public boolean setCache(final String key, Object value, Long expireTime) {
  boolean result =
  ValueOperations&Serializable, Object& operations = redisTemplate
  .opsForValue();
  operations.set(key, value);
  redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
  result =
  } catch (Exception e) {
  e.printStackTrace();
  public void setRedisTemplate(
  RedisTemplate&Serializable, Object& redisTemplate) {
  this.redisTemplate = redisT
  3.6、单元测试相关类:
  package com.luo.baseT
  import org.junit.runner.RunW
  import org.springframework.test.context.ContextC
  import org.springframework.test.context.junit4.AbstractJUnit4SpringContextT
  import org.springframework.test.context.junit4.SpringJUnit4ClassR
  //指定bean注入的配置文件
  @ContextConfiguration(locations = { &classpath:application.xml& })
  //使用标准的JUnit @RunWith注释来告诉JUnit使用Spring TestRunner
  @RunWith(SpringJUnit4ClassRunner.class)
  public class SpringTestCase extends AbstractJUnit4SpringContextTests {
  package com.luo.
  import org.junit.T
  import org.springframework.beans.factory.annotation.A
  import com.luo.baseTest.SpringTestC
  public class RedisTestServiceTest extends SpringTestCase {
  @Autowired
  private RedisTestService redisTestS
  public void getTimestampTest() throws InterruptedException{
  System.out.println(&第一次调用:& + redisTestService.getTimestamp(&param&));
  Thread.sleep(2000);
  System.out.println(&2秒之后调用:& + redisTestService.getTimestamp(&param&));
  Thread.sleep(11000);
  System.out.println(&再过11秒之后调用:& + redisTestService.getTimestamp(&param&));
  3.7、运行结果:
  四、源码下载
  http://download.csdn.net/detail/u03316
【今日微信公号推荐↓】
更多推荐请看《》
  其中推荐了包括技术、设计、极客和IT相亲相关的热门公众号。技术涵盖:Python、Web前端、Java、安卓、iOS、PHP、C/C++、.NET、Linux、数据库、运维、大数据、算法、IT职场等。点击《》,发现精彩!
欢迎举报抄袭、转载、暴力色情及含有欺诈和虚假信息的不良文章。
请先登录再操作
请先登录再操作
微信扫一扫分享至朋友圈
搜狐公众平台官方账号
生活时尚&搭配博主 /生活时尚自媒体 /时尚类书籍作者
搜狐网教育频道官方账号
全球最大华文占星网站-专业研究星座命理及测算服务机构
主演:黄晓明/陈乔恩/乔任梁/谢君豪/吕佳容/戚迹
主演:陈晓/陈妍希/张馨予/杨明娜/毛晓彤/孙耀琦
主演:陈键锋/李依晓/张迪/郑亦桐/张明明/何彦霓
主演:尚格?云顿/乔?弗拉尼甘/Bianca Bree
主演:艾斯?库珀/ 查宁?塔图姆/ 乔纳?希尔
baby14岁写真曝光
李冰冰向成龙撒娇争宠
李湘遭闺蜜曝光旧爱
美女模特教老板走秀
曝搬砖男神奇葩择偶观
柳岩被迫成赚钱工具
大屁小P虐心恋
匆匆那年大结局
乔杉遭粉丝骚扰
男闺蜜的尴尬初夜
客服热线:86-10-
客服邮箱:11173人阅读
Oracle 性能优化(52)
&&& 数据库连接的客户端异常断开后,其占有的相应并没有被释放,如从v$session视图中依旧可以看到对应的session处于inactive,且对应的服务器进程也没有释放,导致资源长时间地被占用,对于这种情形开该如何处理呢?SQLNET.EXPIRE_TIME对于这个问题我们提供了解决方案,专门用于清理那些异常断开的情形,如网络异常中断,客户端异常掉电,异常重启等。本文描述了设置SQLNET.EXPIRE_TIME参数以及演示死连接以及资源被释放的情形。&1、理解SQLNET.EXPIRE_TIME参数&&&Use parameter SQLNET.EXPIRE_TIME to specify a the time interval, in minutes, to send a probe to verify that client/server&&&connections are active.&&&Setting a value greater than 0 ensures that connections are not left open indefinitely, due to an abnormal client termination. &&&If the probe finds a terminated connection,&or a connection that is no longer in use, it returns an error, causing the &&&server process to exit. &&&This parameter is primarily intended for the database server,which typically handles multiple connections at any one time.&&&&&&通过设定参数为非零值(分钟)来发送探测包以检查客户端的异常断开。一旦探测包找到了异常的连接将返回错误,清除对应的server process&&&下面是参数使用的一些限制。(缺省值为0,最小值0,建议值10。SQLNET.EXPIRE_TIME=10)&&&Limitations on using this terminated connection detection feature are:&&&&&&&&&It is not allowed on bequeathed connections.&&&&&&Though very small, a probe packet generates additional traffic that may downgrade network performance.&&&&&&Depending on which operating system is in use, the server may need to perform additional processing to distinguish&&&&&&the connection probing event from other events that occur. This can also result in degraded network performance.&2、Dead Connection Detection (DCD)与Inactive SessionsDead connections:&&&These are previously valid connections with the database but the connection between the client and server processes has&&&terminated abnormally.&&&Examples of a dead connection:&&&- A user reboots/turns-off their machine without logging off or disconnecting from the database.&&&- A network problem prevents communication between the client and the server.&&&&&&In these cases, the shadow process running on the server and the session in the database may not terminate.&&&&&&Implemented by &&&&&&&& * adding SQLNET.EXPIRE_TIME = &MINUTES& to the sqlnet.ora file &&&&&&With DCD is enabled, the Server-side process sends a small 10-byte packet to the client process after the duration of &&&the time interval specified in minutes by the SQLNET.EXPIRE_TIME parameter.&&&&&&If the client side connection is still connected and responsive, the client sends a response packet back to the database&&&server, resetting the timer..and another packet will be sent when next interval expires (assuming no other activity on &&&the connection).&&&&&&If the client fails to respond to the DCD probe packet&&&&&&& * the Server side process is marked as a dead connection and &&&&&&& * PMON performs the clean up of the database processes / resources&&&&&&& * The client OS processes are terminated&&&&&&NOTE: SQLNET.RECV_TIMEOUT can be set on the SERVER side sqlnet.ora file. This will set a timeout for the server process &&&&&&&& to wait for data from the client process. Inactive Sessions:&&&These are sessions that remain connected to the database with a status in v$session of INACTIVE.&&&Example of an INACTIVE session:&&&- A user starts a program/session, then leaves it running and idle for an extended period of time.&3、配置SQLNET.EXPIRE_TIME#对于SQLNET.EXPIRE_TIME的配置,需要修改sqlnet.ora,然后添加SQLNET.EXPIRE_TIME项
[oracle@orasrv admin]$ more sqlnet.ora
sqlnet.expire_time = 1
#仅仅需要配置此项,后面的各项仅仅是为了生成跟踪日志,可省略
TRACE_LEVEL_SERVER = 16
TRACE_FILE_SERVER = SERVER
TRACE_DIRECTORY_SERVER= /u01/app/oracle/network/trace
TRACE_TIMESTAMP_ SERVER = ON
TRACE_UNIQUE_SERVER = ON
DIAG_ADR_ENABLED=OFF
4、模拟及测试DCD连接C:\Users\robinson.cheng&sqlplus scott/tiger@ora11g
---&从windows客户端发起连接
SQL*Plus: Release 11.2.0.1.0 Production on Tue Jun 25 09:57:59 2013
Copyright (c) , Oracle.
All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
---Issued the sql to hold a lock
SQL& update emp set sal=sal*1.1 where deptno=20;
5 rows updated.
--disabled the network adapter in VM setting
SQL& select *
select * from dual
ERROR at line 1:
ORA-03113: end-of-file on communication channel
Process ID: 29522
Session ID: 15 Serial number: 447
--服务器端环境
SQL& select * from v$version where rownum&2;
--------------------------------------------------------------------------------
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
--在服务器端查看session的情况,SCOTT用户的session状态为INACTIVE
SQL& @comm_sess_
+----------------------------------------------------+
| User Sessions (All)
+----------------------------------------------------+
SID Serial ID
Status Oracle User
O/S User O/S PID Session Program
--------- ------ --------- --------- ----------- ------------ ------- -------------------------- ---------- -------------
SCOTT Robinson.Che
29522 sqlplus.exe
TRADESZ\PC39
--Get the spid for user scott by SID
SQL& @my_spid_from_sid
Enter value for input_sid: 15
4: AND s.sid = &input_sid
4: AND s.sid = 15
SERIAL# SPID
------ ---------- ------------------------
--To find the locked object
SQL& @lock_obj
OBJECT_NAME||''||LOCKED_MODE||''||CTIME||''||C.SID||''||SERIAL#
------------------------------------------------------------------
--The trace file exists
SQL& ho ls -hltr /u01/app/oracle/network/trace/s*29522*
-rw-r----- 1 oracle oinstall 241K Jun 25 09:59 /u01/app/oracle/network/trace/server_29522.trc
---&try to issue another sql. the sql is blocked
10:03:46 SQL& delete scott.emp where deptno=20;
delete scott.emp where deptno=20
ERROR at line 1:
ORA-01013: user requested cancel of current operation
--Check the server process for scott
10:04:37 SQL& ho ps -ef | grep 29522 | grep -v grep
00:00:00 oracleora11g (LOCAL=NO)
--Could not reach to client from server.
10:06:51 SQL& ho ping 192.168.7.133
PING 192.168.7.133 (192.168.7.133) 56(84) bytes of data.
From 192.168.7.40 icmp_seq=2 Destination Host Unreachable
From 192.168.7.40 icmp_seq=3 Destination Host Unreachable
From 192.168.7.40 icmp_seq=4 Destination Host Unreachable
From 192.168.7.40 icmp_seq=6 Destination Host Unreachable
From 192.168.7.40 icmp_seq=7 Destination Host Unreachable
From 192.168.7.40 icmp_seq=8 Destination Host Unreachable
--此时总进程数为27个
10:15:08 SQL& select count(*) from v$
----------
--从09:58进程启动开始到10:17:59进程依旧没有被释放
10:17:59 SQL& ho ps -ef | grep 29522 | grep -v grep
00:00:00 oracleora11g (LOCAL=NO)
--&At this time the server process was released
10:18:08 SQL& ho ps -ef | grep 29522 | grep -v grep
--进程释放后此时进程总数变为26个
10:19:45 SQL& select count(*) from v$
----------
--&the lock was released
10:19:54 SQL& @lock_obj
no rows selected
--Author : Robinson
: http://blog.csdn.net/robinson_0612
--scott用户的session已经从v$session中被移除
10:20:03 SQL& @comm_sess_
+----------------------------------------------------+
| User Sessions (All)
+----------------------------------------------------+
SID Serial ID
Oracle User
O/S User O/S PID Session Program
--------- ------ --------- --------- -------------- ------------ ------- -------------------------- -------- ----------
5、查看SQLNET.EXPIRE_TIME是否启用#下面对跟踪日志过滤,可以看到09:58:02:853中提示开启dead connection detection
[oracle@orasrv trace]$ cat -n server_29522.trc |grep dead
[25-JUN-:02:853] niotns: Enabling dead connection detection (1 min)
#下面的查询中,在09:58:03 timer被启动,10:18:26后,连接被彻底关闭(包括server process)
[oracle@orasrv trace]$ cat -n server_29522.trc |grep timer
[25-JUN-:03:050] nstimstart: starting timer at 25-JUN-:03
[25-JUN-:03:051] nsconbrok: timer created for connection
[25-JUN-:26:173] nstimarmed: timer is armed, with value 3833
#下面是starting timer的详细信息
[oracle@orasrv trace]$ head -451 server_29522.trc | tail -5
[25-JUN-:03:050] nstimstart: starting timer at 25-JUN-:03
[25-JUN-:03:051] nstimset: entry
[25-JUN-:03:051] nstimset: normal exit
[25-JUN-:03:051] nstimstart: normal exit
[25-JUN-:03:051] nsconbrok: timer created for connection
#下面是timer被清除后的详细信息nstimclear: normal exit
[oracle@orasrv trace]$ head -4097 server_29522.trc | tail -7
[25-JUN-:26:173] nstimarmed: entry
[25-JUN-:26:173] nstimarmed: timer is armed, with value 3833
[25-JUN-:26:173] nstimarmed: normal exit
[25-JUN-:26:173] nstimclear: entry
[25-JUN-:26:173] nstimclear: normal exit
[25-JUN-:26:173] nttctl: entry
[25-JUN-:26:173] nttctl: entry
6、小结a、DCD连接通常指用户没有正常断开连接而重启客户端,关机以及网络问题导致客户端无法与服务器正常通信所致的连接b、相对于DCD连接,INACTIVE session则是用户建立连接之后,尚未执行任何操作或操作已经完成但没有断开,等同于与处于idle状态c、无论是DCD连接,还是出于idle状态的INACTIVE session,在v$session视图呈现的都是INACTIVE状态d、对于使用resource_limit及profile配置后用户session超出idle_time的情形,在v$session视图呈现sniped状态e、当在sqlnet.ora配置文件中设置了SQLNET.EXPIRE_TIME参数为非零值时,僵死连接在EXPIRE_TIME指定的时间后被清除f、演示中仅仅设定EXPIRE_TIME为1分钟,而实际的释放时间接近20分钟左右,什么原因尚不清楚,有待进一步测试g、设定SQLNET.EXPIRE_TIME为非零值之后,系统需要产生而外的开销以及带来网络性能的下降h、对于需要及时释放OS及DB资源的情形,Oracle建议的同时并设定SQLNET.EXPIRE_TIME为非零值 i、Reference: [ID ] [ID ] [ID ] [ID ]&&更多参考有关Oracle RAC请参考&&&& &&&& &&&& &&&& &&&& &&&& &&&& &&&& &&&& &&&& &&&&
&&&& &&& &&&&& &&&&&
有关Oracle 网络配置相关基础以及概念性的问题请参考:&&&&
&&&& &&&& 有关基于用户管理的备份和备份恢复的概念请参考&&&& &&&& &&&& &&&& &&&& &&&& &&&& &&&& 有关RMAN的备份恢复与管理请参考&&&& &&&& &&&& &&&& &&&& &&&& &&&& &&&& &&&& &&&& &&&& &&&& 有关ORACLE体系结构请参考&&&& &&&& &&&& &&&& &&&& &&&& &&&& &&&& &&&& &&&& &
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:4252689次
积分:44633
积分:44633
排名:第62名
原创:581篇
评论:682条
QQ: & & &
微信: & & &
博客转载请以链接注明出处
(4)(4)(1)(8)(2)(11)(9)(1)(5)(1)(6)(5)(2)(2)(1)(4)(8)(11)(3)(4)(1)(5)(14)(3)(7)(6)(16)(4)(19)(11)(4)(4)(4)(7)(10)(3)(4)(5)(5)(8)(7)(11)(13)(13)(9)(13)(14)(15)(9)(7)(18)(9)(12)(7)(4)(1)(1)(7)(7)(8)(2)(6)(4)(8)(9)(3)(3)(9)(6)(7)(2)(4)(6)(8)(20)(11)(7)(2)(7)(12)(5)(10)(10)(6)(2)(1)(3)(3)2021人阅读
.net(66)
windows下的&&安装的exe文件。(此exe文件已经打包了所需的dll了,即exe中包含dll组件)
2.安装步骤
&一、缓存服务Memcached-1.4.5(W64)安装步骤:
1. 将Memcached-1.4.5(W64)解压放某个盘下面,比如在
E:\ApabiCourse\memcached\memcached-1.4.5(W64).exe;
2. 在运行中启动CMD,然后输入
【“E:\ApabiCourse\memcached\memcached-1.4.5(W64).exe” -d install】 安装;
3. 在运行下输入“regedit”打开注册表, &找到路径&HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\memcached,下面找到一个ImagePath 的字符串项,正好是服务的执行路径的字符串,双击该串,在后面追加入“-m 2048 -c 20000”( 使用2048M内存,链接数为20000)。
4. 再输入:【“E:\ApabiCourse\memcached\memcached-1.4.5(W64).exe”-d start】启动。 以后memcached将作为windows的一个服务每次开机时自动启动。这样服务器端已经安装完毕了。
检测是否安装成功
5.检测服务是否可用:
&执行cmd命令,启动telnet到memcached服务所在的ip的端口,例如【telnet 172.18.89.5 11211】,其中,11211是memcached的默认端口
输入stats,即可看到下图,证明安装服务成功。
常用命令:
将memcached.exe安装为Windows服务:memcached.exe -d install
启动memcached服务:memcached.exe -d start
启动memcached服务(windows命令):net start &memcached Server&
停止memcached服务(windows命令):net stop &memcached Server&
连接到memcached控制台:telnet ServerIP 11211
打印当前memcached服务器状态:stats
打印当前memcached服务器Items(记录)的统计信息:stats items
打印当前memcached服务器Slab(分区)及Chunk(块)的统计信息:stats slabs
打印指定Slab中的KEY列表(可用于遍历items,但效率较低,慎用!):stats cachedump&SlabId&Limit_num。显示结果:ITEM&KeyName&[ValueByteLength&b;&LastAccessTime&s]。值得注意的是,经过测试确认:那个LastAccessTime并不是记录到期时间,而是最后一次的get时间,并且get之后,也不会自动延长expiry(到期时间)。
添加新记录:add&KeyName&0
0&ValueByteLength&[回车]&ValueContent
删除记录 :&delete&KeyName
添加或更新记录 :&set&KeyName&0
0&ValueByteLength&[回车]&ValueContent
更新记录 :&replace&KeyName&0
0&ValueByteLength&[回车]&ValueContent
通过这个数据我们就可以了解Memcached的状态了。
这些数据所代表的意义如下:
pid:32u,服务器进程ID。
uptime:32u, 服务器运行时间,单位秒。
time :32u, 服务器当前的UNIX时间。
version :string, 服务器的版本号。
curr_items :32u, 服务器当前存储的内容数量 Current number of items stored by the server
total_items :32u, 服务器启动以来存储过的内容总数。
bytes :64u, 服务器当前存储内容所占用的字节数。
curr_connections :32u, 连接数量。
total_connections :32u, 服务器运行以来接受的连接总数。
connection_structures:32u, 服务器分配的连接结构的数量。
cmd_get :32u, 取回请求总数。
cmd_set :32u, 存储请求总数。
get_hits :32u, 请求成功的总次数。
get_misses :32u, 请求失败的总次数。
bytes_read :64u, 服务器从网络读取到的总字节数。
bytes_written :64u, 服务器向网络发送的总字节数。
limit_maxbytes :32u, 服务器在存储时被允许使用的字节总数。
上面的描述中32u和64u表示32位和64位无符号整数,string表示是string类型数据。
三、memcache客户端的安装(.net版本)
& Memcached Client
源码地址:&&&&&&&
(开源项目,可提供研究学习)
Enyim也是应用比较广泛的Memcached .net客户端,和之前的Memchachedonet 客户端相比,分布式算法应该做了相应优化
下载 Memcached Client 和 Memcached Providers,解压后会发现, Memcached Client中,还包含了著名的Log4net日志框架。
而Memcached Providers中其实包含了Enyim.Caching.dll,也包含了Log4netDLL。
Memcached Providers更强大,MemcachedProviders是对Enyim.Caching的再次封装,并加入了客户端计数器功能以及Session数据库管理功能。
当然,使用和配置起来也同样简单,方便,只是对于一些负责的操作和处理方面,功能更强大一些。
如果只是简单的应用,推荐直接使用 Memcached Client。除了添加必要的Enyim.Caching.dll引用,还需要修改应用程序的配置文件。
下面的代码贴出这两种方式的配置文件和测试代码:(放心,有详细的注释)
测试代码(实现最简单的功能)
using System.Collections.G
using System.L
using System.W
using System.Web.UI;
using System.Web.UI.WebC
using Enyim.C
using MemcachedProviders.C
using System.T
namespace MemcachedProject
public partial class _Default : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
testMemcachedProviders();
/// &summary&
/// 测试Enyim.Caching(注意:Enyim.Caching只具有MemcachedProviders的一部分功能,后者更强大。还可以集成Log4Net日志框架)
/// &/summary&
public void testEnyimCaching()
MemcachedClient client = new MemcachedClient(&/memcached&);
//存值
--不带过期时间的存储,Memcached将根据LRU来决定过期策略
bool result = client.Store(Enyim.Caching.Memcached.StoreMode.Add, &name&, &dinglang&);
//带过期时间的缓存
//bool success = client.Store(StoreMode.Add, person.UserName, person, DateTime.Now.AddMinutes(10));
if (result)
Response.Write(&成功存入缓存&);
//取值
object name = client.Get(&name&);
if (name != null)
Response.Write(&取出的值为:& + name);
Response.Write(&取值失败&);
Response.Write(&存入缓存失败&);
/// &summary&
/// 使用MemcachedProviders客户端
/// &/summary&
public void testMemcachedProviders()
string key = &myName&;
string value = &Dylan&;
bool result = false;
string val = string.E
#region 存/取最简单的数据类型
//如果缓存中没有,就尝试着去存入缓存
if (DistCache.Get(key) == null)
//DistCache.DefaultExpireTime = 1200;//缓存时间
result = DistCache.Add(key, value);
if (result)
//如果存入成功,就试着去取
Thread.Sleep(500);
string ret = (string)DistCache.Get(key);
//Assert.AreEqual(value, ret);
if (ret != null)
Response.Write(ret);
Response.Write(&&br/&&);
//取出来的值为null,直接移除该缓存对象
DistCache.Remove(key);//移除
// DistCache.RemoveAll();//移除所有
//缓存中有,直接拿数据
string ret = (string)DistCache.Get(key);
if (ret != null)
Response.Write(ret);
Response.Write(&&br/&&);
DistCache.Remove(key);
#endregion
存/取一个Person对象
Person person = new Person() { Id = 007, Name = &Dylan& };//new 一个Person对象的实例
//如果缓存中没有,则尝试着放入缓存
if (DistCache.Get&Person&(&myObj&) == null)
result = DistCache.Add(&myObj&, person);
if (result)
Thread.Sleep(500);
val = DistCache.Get(&myObj&).ToString();
if (val != null)
Response.Write(val);
Response.Write(&&br/&&);
DistCache.Remove(&myObj&);
//缓存中已经有该对象,就直接从缓存取
Person p = DistCache.Get&Person&(&myObj&);
val = person.ToString();
//也可以直接这样取
// val = DistCache.Get(&myObj&).ToString();
if (val != null)
Response.Write(val);
Response.Write(&&br/&&);
DistCache.Remove(&myObj&);
#endregion
Person类的定义代码:
这里需要说明的是如果我们需要向Memcached中添加自定义数据类型时,我们需要将该数据类型添加上[Serializable]标记。
[Serializable]
public class Person
private int
public int Id
get { return
set { id = value; }
private string
public string Name
get { return
set { name = value; }
/// &summary&
/// 重写Tostring(),方便输出验证
/// &/summary&
/// &returns&&/returns&
public override string ToString()
return &Person:& + &{name:& + Name + &,id:& + Id + &}&;
web.config 配置信息:
&?xml version=&1.0&?&
有关如何配置 ASP.NET 应用程序的详细信息,请访问
/fwlink/?LinkId=169433
&configuration&
&!--Enyim.Caching配置(省略了Log4Net框架)
For Memcached--&
&!--&configSections&
&sectionGroup name=&&&
&section name=&memcached& type=&Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching& /&
&/sectionGroup&
&/configSections&
& protocol=&Binary&&
&memcached&
&add address=&127.0.0.1& port=&11121&
&/servers&
&socketPool minPoolSize=&10& maxPoolSize=&100& connectionTimeout=&00:00:10& deadTimeout=&00:02:00& /&
&/memcached&
&!--The Enyim.Caching配置 End --&
&!--MemcachedProviders的配置
&configSections&
&section name=&cacheProvider& type=&MemcachedProviders.Cache.CacheProviderSection, MemcachedProviders&
allowDefinition=&MachineToApplication& restartOnExternalChanges=&true&/&
&sectionGroup name=&&&
&section name=&memcached& type=&Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching& /&
&/sectionGroup&
&section name=&log4net& type=&log4net.Config.Log4NetConfigurationSectionHandler,log4net&/&
&/configSections&
&cacheProvider defaultProvider=&MemcachedCacheProvider&&
&providers&
&add name=&MemcachedCacheProvider&
type=&MemcachedProviders.Cache.MemcachedCacheProvider, MemcachedProviders&
keySuffix=&_MySuffix_& defaultExpireTime=&2000&/&
&/providers&
&/cacheProvider&
&memcached&
&!-- put your own server(s) here--&
&add address=&127.0.0.1& port=&11121& /&
&/servers&
&socketPool minPoolSize=&10& maxPoolSize=&100& connectionTimeout=&00:00:10& deadTimeout=&00:02:00& /&
&/memcached&
&appender name=&ConsoleAppender& type=&log4net.Appender.ConsoleAppender&&
&layout type=&log4net.Layout.PatternLayout&&
&conversionPattern value=&%date [%thread] %-5level %logger [%property{NDC}]- %message%newline& /&
&/appender&
&priority value=&WARN&/&
&appender-ref ref=&ConsoleAppender&&
&filter type=&log4net.Filter.LevelRangeFilter&&
&levelMin value=&WARN&/&
&levelMax value=&FATAL&/&
&/appender-ref&
&/log4net&
&!--The MemcachedProviders配置 End
配置结束,下面的都是一些其他的配置,例如连数据库之类的,和我们的
memcache 无关--&
&connectionStrings&
&add name=&ApplicationServices&
connectionString=&data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.User Instance=true&
providerName=&System.Data.SqlClient& /&
&/connectionStrings&
&system.web&
&compilation debug=&true& targetFramework=&4.0& /&
&authentication mode=&Forms&&
&forms loginUrl=&~/Account/Login.aspx& timeout=&2880& /&
&/authentication&
&membership&
&providers&
&add name=&AspNetSqlMembershipProvider& type=&System.Web.Security.SqlMembershipProvider& connectionStringName=&ApplicationServices&
enablePasswordRetrieval=&false& enablePasswordReset=&true& requiresQuestionAndAnswer=&false& requiresUniqueEmail=&false&
maxInvalidPasswordAttempts=&5& minRequiredPasswordLength=&6& minRequiredNonalphanumericCharacters=&0& passwordAttemptWindow=&10&
applicationName=&/& /&
&/providers&
&/membership&
&providers&
&add name=&AspNetSqlProfileProvider& type=&System.Web.Profile.SqlProfileProvider& connectionStringName=&ApplicationServices& applicationName=&/&/&
&/providers&
&/profile&
&roleManager enabled=&false&&
&providers&
&add name=&AspNetSqlRoleProvider& type=&System.Web.Security.SqlRoleProvider& connectionStringName=&ApplicationServices& applicationName=&/& /&
&add name=&AspNetWindowsTokenRoleProvider& type=&System.Web.Security.WindowsTokenRoleProvider& applicationName=&/& /&
&/providers&
&/roleManager&
&/system.web&
&system.webServer&
&modules runAllManagedModulesForAllRequests=&true&/&
&/system.webServer&
&/configuration&
/whoknows/articles/memcache_php5-3-10_win32.html& introduce
/memcached-144-windows-32-bit-binary-now-available& down
/luminji/archive//2140804.html& winform example
/zhoufoxcn/archive//2515609.html& 周公
/p/memcached/wiki/NewServerMaint google
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:353348次
积分:4813
积分:4813
排名:第4934名
原创:110篇
转载:137篇
评论:67条
(1)(3)(3)(2)(4)(2)(1)(1)(2)(1)(4)(1)(1)(1)(1)(1)(1)(1)(2)(4)(1)(1)(1)(1)(3)(3)(4)(1)(4)(1)(3)(1)(4)(3)(3)(2)(2)(4)(8)(2)(4)(1)(1)(4)(1)(4)(4)(2)(3)(1)(2)(1)(1)(1)(2)(3)(4)(3)(1)(2)(2)(1)(1)(2)(1)(2)(1)(3)(1)(2)(1)(1)(7)(4)(2)(3)(6)(6)(3)(4)(1)(3)(12)(1)(1)(2)(3)(12)(25)(1)}

我要回帖

更多关于 timeexpire 时间过短 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信