通过spring.net中的spring.caching CacheResult实现memcached缓存
通过spring.net中的spring.caching CacheResult实现memcached缓存
1.SpringMemcachedCache.cs
2.APP.config
3.Program.cs
4.Common
待解决问题:CacheResult,CacheResultItems有什么区别????
SpringMemcachedCache.cs memcached的实现, 继承了Spring.Caching.AbstractCache, memcached的实现用了Enyim.Caching
using System;
using Spring.Caching;
using System.Web;
using System.Collections;
using System.Web.Caching;
using Enyim.Caching;
using Enyim.Caching.Memcached; namespace Demo.Common
{
/// <summary>
/// An <see cref="ICache"/> implementation backed by ASP.NET Cache (see <see cref="HttpRuntime.Cache"/>).
/// </summary>
/// <remarks>
/// <para>
/// Because ASP.NET Cache uses strings as cache keys, you need to ensure
/// that the key object type has properly implemented <b>ToString</b> method.
/// </para>
/// <para>
/// Despite the shared underlying <see cref="HttpRuntime.Cache"/>, it is possible to use more than
/// one instance of <see cref="AspNetCache"/> without interfering each other.
/// </para>
/// </remarks>
/// <author>Aleksandar Seovic</author>
/// <author>Erich Eichinger</author>
public class SpringMemcachedCache : AbstractCache
{
#region Fields // logger instance for this class
private static MemcachedClient memcachedClient = null;
private static object initLock = new object(); #endregion private MemcachedClient MemcachedClient
{
get
{
if (memcachedClient == null)
{
lock (initLock)
{
if (memcachedClient == null)
{
memcachedClient = new MemcachedClient();
}
}
} return memcachedClient;
}
} /// <summary>
/// Retrieves an item from the cache.
/// </summary>
/// <param name="key">
/// Item key.
/// </param>
/// <returns>
/// Item for the specified <paramref name="key"/>, or <c>null</c>.
/// </returns>
public override object Get(object key)
{
object result = key == null ? null : MemcachedClient.Get(GenerateKey(key));
return result;
} /// <summary>
/// Removes an item from the cache.
/// </summary>
/// <param name="key">
/// Item key.
/// </param>
public override void Remove(object key)
{
if (key != null)
{
MemcachedClient.Remove(GenerateKey(key));
}
} /// <summary>
/// Inserts an item into the cache.
/// </summary>
/// <param name="key">
/// Item key.
/// </param>
/// <param name="value">
/// Item value.
/// </param>
/// <param name="timeToLive">
/// Item's time-to-live (TTL).
/// </param>
protected override void DoInsert(object key, object value, TimeSpan timeToLive)
{
MemcachedClient.Store(StoreMode.Set, GenerateKey(key), value, timeToLive);
} /// <summary>
/// Generate a key to be used for the underlying <see cref="Cache"/> implementation.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GenerateKey(object key)
{
return key.ToString();
} public override ICollection Keys
{
get { throw new NotSupportedException(); }
}
}
}
APP.config 配置enyim.com, memcache, spring.net
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="enyim.com">
<section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching"/>
<!-- log -->
<section name="log" type="Enyim.Caching.Configuration.LoggerSection, Enyim.Caching" />
</sectionGroup> <sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections> <enyim.com>
<memcached>
<servers>
<add address="127.0.0.1" port=""/>
</servers>
<socketPool minPoolSize="" maxPoolSize="" connectionTimeout="00:00:10" deadTimeout="00:02:00"/>
</memcached>
</enyim.com> <spring>
<context>
<resource uri="config://spring/objects" />
</context>
<objects xmlns="http://www.springframework.net" >
<object id="CacheAspect" type="Spring.Aspects.Cache.CacheAspect, Spring.Aop"/>
<object id="autoBOProxyCreator" type="Spring.Aop.Framework.AutoProxy.ObjectNameAutoProxyCreator, Spring.Aop">
<property name="ObjectNames">
<list>
<value>*BO</value>
</list>
</property>
<property name="InterceptorNames">
<list>
<value>CacheAspect</value>
</list>
</property>
</object> <object id="cachedTestBO" type="Demo.App.CachedTestBO, Demo.App"></object> <object id="MemCachedCache" type="Demo.Common.SpringMemcachedCache, Demo.Common">
<property name="TimeToLive" value="00:05:00"/>
</object> <object id="MemCachedCache-Short" type="Demo.Common.SpringMemcachedCache, Demo.Common">
<property name="TimeToLive" value="00:05:00"/>
</object> <object id="MemCachedCache-Long" type="Demo.Common.SpringMemcachedCache, Demo.Common">
<property name="TimeToLive" value="00:30:00"/>
</object> </objects>
</spring> </configuration>
App Program.cs 测试效果
1.要从spring中进入的才会调用, 直接实例化进入不会调用
2.CacheName - "SpringCache" 对应spring配置中的id="SpringCache"节点,是实现cache的类
3.Key="'prefix.key.'+#cacheId" 传人cachedId=1对应生成以后的key为 prefix.key.1
复杂点的Key组合见下面
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Demo.Common;
using Spring.Caching;
using Spring.Context;
using Spring.Context.Support; namespace Demo.App
{
class Program
{
private static void Main(string[] args)
{
//通过spring.net来调用函数
IApplicationContext ctx = ContextRegistry.GetContext(); IDictionary testDictionary = ctx.GetObjectsOfType(typeof(ITestBO));
foreach (DictionaryEntry entry in testDictionary)
{
string name = (string)entry.Key;
ITestBO service = (ITestBO)entry.Value;
Console.WriteLine(name + " intercept: ");
//第一次运行函数并保存到memcached
Console.WriteLine("nowTime:" + DateTime.Now.ToString("T")
+ " testTime:" +service.TestMethod(, new object[]{"one", "two"})); Console.WriteLine(); Thread.Sleep(); //休眠5秒以便第二次调用查看是否有保存到memcached //第二次运行从memcached中读取数据
Console.WriteLine("nowTime:" + DateTime.Now.ToString("T")
+ " testTime:" + service.TestMethod(, new object[] { "one", "two" })); Console.WriteLine(); } //手动实例化,不会从memcached中读取数据,因为没有运行到CacheResult中去
ITestBO test = new CachedTestBO();
test.TestMethod(); Console.ReadLine();
}
} public interface ITestBO
{
string TestMethod(int cacheId, params object[] elements);
} public class CachedTestBO : ITestBO
{
//生成的key类似HK-MainSubAccountMap-1
[CacheResult(CacheName = SpringCache.NormalCache,
Key = SpringCache.SpringCacheCountryPrefix
+"+'" + SpringCacheKey.MainSubAccountMap + "'"
+ "+'-' + #cacheId")]
public string TestMethod(int cacheId, params object[] elements)
{
return DateTime.Now.ToString("T");
}
} }
Common类
namespace Demo.Common
{
public static class ApplicationVariables
{
private static string countryCode;
public static string CountryCode
{
get
{
if (countryCode == null)
{
countryCode = "HK";
}
return countryCode;
}
}
} public static class SpringCache
{
public const string SpringCacheCountryPrefix = @"T(Demo.Common.ApplicationVariables).CountryCode + '-'";
public const string NormalCache = "MemCachedCache"; public const string AspnetCache = "AspnetCache";
} public static class SpringCacheKey
{
public const string MainSubAccountMap = "MainSubAccountMap"; public const string BOSetting = "BOSetting";
}
}
通过spring.net中的spring.caching CacheResult实现memcached缓存的更多相关文章
- Spring MVC 中的http Caching
文章目录 过期时间 Last-Modified ETag Spring ETag filter Spring MVC 中的http Caching Cache 是HTTP协议中的一个非常重要的功能,使 ...
- Spring Framework------>version4.3.5.RELAESE----->Reference Documentation学习心得----->Spring Framework中的spring web MVC模块
spring framework中的spring web MVC模块 1.概述 spring web mvc是spring框架中的一个模块 spring web mvc实现了web的MVC架构模式,可 ...
- Spring Boot中使用 Spring Security 构建权限系统
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中配置的Bean,为应用系统提供声明式的安全 ...
- Spring Boot 中应用Spring data mongdb
摘要 本文主要简单介绍下如何在Spring Boot 项目中使用Spring data mongdb.没有深入探究,仅供入门参考. 文末有代码链接 准备 安装mongodb 需要连接mongodb,所 ...
- 如何在静态方法或非Spring Bean中注入Spring Bean
在项目中有时需要根据需要在自己new一个对象,或者在某些util方法或属性中获取Spring Bean对象,从而完成某些工作,但是由于自己new的对象和util方法并不是受Spring所 ...
- Spring Boot中使用Spring Security进行安全控制
我们在编写Web应用时,经常需要对页面做一些安全控制,比如:对于没有访问权限的用户需要转到登录表单页面.要实现访问控制的方法多种多样,可以通过Aop.拦截器实现,也可以通过框架实现(如:Apache ...
- 【swagger】1.swagger提供开发者文档--简单集成到spring boot中【spring mvc】【spring boot】
swagger提供开发者文档 ======================================================== 作用:想使用swagger的同学,一定是想用它来做前后台 ...
- Spring Boot中集成Spring Security 专题
check to see if spring security is applied that the appropriate resources are permitted: @Configurat ...
- 在非spring组件中注入spring bean
1.在spring中配置如下<context:spring-configured/> <context:load-time-weaver aspectj-weaving=&q ...
随机推荐
- Android———从GitHub上下载源码的方法【Written By KillerLegend】
首先声明,本文说的是从GitHub上下载源码而非上传源码! 1:下载tortoisegit,下载地址为: https://code.google.com/p/tortoisegit/wiki/Down ...
- Python基础 第二天
1.http://www.cnblogs.com/beer/p/5672678.html requests和beautifulsoup
- 開賣!下集 -- ASP.NET 4.5 專題實務(II)-範例應用與 4.5新功能【VB/C# 雙語法】
開賣!下集 -- ASP.NET 4.5 專題實務(II)-範例應用與 4.5新功能[VB/C# 雙語法] 我.....作者都沒拿到書呢! 全台灣最專業的電腦書店 -- 天瓏書局 已經開賣了! 感謝天 ...
- clojure
ide http://updatesite.ccw-ide.org/stable https://cursiveclojure.com/ http://web.clojurerepl.com/ htt ...
- 窗体皮肤实现 - 实现简单Toolbar(六)
自定义皮肤很方便,基础开发的工作也是很大的.不过还好一般产品真正需要开发的并不是很多.现在比较漂亮的界面产品都会有个大大的工具条. Toolbar工具条实现皮肤的方法还是可以使用Form的处理方案.每 ...
- linux kernel同步机制的思考
在学习内核同步机制的时候,书中介绍了同步方法:原子操作(atomic).自旋锁(spinlock).信号量(semaphore).互斥锁(mutex).完成变量(completion).大内核(BLK ...
- oracle 11g 表空间使用率
Oracle数据库表空间使用量查询: select b.file_name 物理文件名,b.tablespace_name 表空间,b.bytes/1024/1024 大小M,(b.bytes-sum ...
- outlook配置
有时打开outlook报错.步骤如下: 一.打开控制面板-邮件-电子邮件账户-新建 二.具体设置如下: 三.点第二步上的“其他设置(M)”.做发送服务器.
- MYSQL主键存在则更新,不存在则插入的解决方案(ON DUPLICATE KEY UPDATE)
经常我们使用的最简单的数据库操作就是数据的更新,删除和插入,对于批量删除和插入的方法相信大家都很清楚,那么批量更新估计有的人就不知道了,并且还有批量插入,在插入时若有主键冲突则更新的操作,这在EAV模 ...
- (转)redis 学习笔记(1)-编译、启动、停止
redis 学习笔记(1)-编译.启动.停止 一.下载.编译 redis是以源码方式发行的,先下载源码,然后在linux下编译 1.1 http://www.redis.io/download 先 ...