Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*
 * Cache 接口,实现tag功能,key前缀
 * Logs,Memcached 在这里没有公开,只是一些具体的实现,你可以根据已经情况实现一下
 * Logs.Debug 表示写debug日志
 * Memcached 里面的Get,Set,Remove也需要自已实现
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class Caches
{	
	
	private static string GenerateKey(string key)
	{
	    return "project_name/" + key;
	}
	
	/// <summary>
	/// 取缓存
	/// </summary>
	/// <param name="key"></param>
	/// <returns></returns>
	public static object Get(string key)
	{
	    key = GenerateKey(key);
	
	    object obj = Memcached.Get(key);
	    
	    if (obj != null)
	    {
	
	        Logs.Debug("Cache hit " + key);
	    }
	
	    return obj;
	}
	
	/// <summary>
	/// 存缓存
	/// </summary>
	/// <param name="key"></param>
	/// <param name="value"></param>
	public static void Set(string key, object value)
	{
	    key = GenerateKey(key);
	
	    Memcached.Caches.Set(key, value);
	
	    Logs.Debug("Cache set " + key);
	}
	
	/// <summary>
	/// 存缓存,带Tag,用于做类似命名空间的管理
	/// </summary>
	/// <param name="key"></param>
	/// <param name="value"></param>
	/// <param name="tags"></param>
	public static void Set(string key, object value, string[] tags)
	{
	    if (tags.Length == 0)
	    {
	        Set(key, value);
	    }
	
	    for (int i = 0; i < tags.Count(); i++)
	    {
	        tags[i] = "tags/" + tags[i];
	    }
	
	    List<string> tagList = new List<string>();
	    foreach (string tag in tags)
	    {
	        object tagObj = Get(tag);
	        if (tagObj != null)
	        {
	            tagList = (List<string>)tagObj;                    
	        }
	
	        tagList.Add(key);
	        Set(tag, tagList);
	    }
	
	    Set(key, value);
	}
	
	
	/// <summary>
	/// 删缓存
	/// </summary>
	/// <param name="key"></param>
	public static void Remove(string key)
	{
	    key = GenerateKey(key);
	
	    Memcached.Remove(key);
	
	    Logs.Debug("Cache remove " + key);
	}
	
	/// <summary>
	/// 根据 Tag 删除缓存
	/// </summary>
	/// <param name="tags"></param>
	public static void RemoveByTags(string[] tags)
	{
	    for (int i = 0; i < tags.Count(); i++)
	    {
	        tags[i] = "tags/" + tags[i];
	    }
	
	    List<string> tagList = new List<string>();
	    foreach (string tag in tags)
	    {
	        object tagsObj = Get(tag);
	        if (tagsObj != null)
	        {
	            tagList = (List<string>)tagsObj;
	            foreach (string key in tagList)
	            {
	                Remove(key);
	            }
	        }
	
	        Remove(tag);
	    }
	}
}