首页 新闻 搜索 专区 学院

Memcache缓存问题

0
悬赏园豆:5 [已关闭问题] 关闭于 2016-02-17 16:42

请教各位,我在本机上安装了memcache服务器,另外,在本机上创建了2个.net网站,网站中,进入了MemcacheHelper一个专门用来与服务器通信的类,其中一个网站

  1 网站一中:专门取缓存的方法 
  2  public void GetCatch()
  3         {
  4             Label1.Visible = false;
  5             string key = "user";//key值
  6             object obj = new object();
  7             if (MemcacheHelper.IsCache(key))
  8             {
  9                 obj = MemcacheHelper.GetCache(key);
 10                 Users u = (obj) as Users;
 11                 TextBox1.Text = u.name;
 12                 TextBox2.Text = u.note;
 13             }
 14             else
 15             {
 16                 Label1.Visible = true;
 17             }
 18         }
 19 网站二中:专门设置缓存的方法
 20  protected void btnupdate_Click(object sender, EventArgs e)
 21         {
 22             Users u = new Users();
 23             u.name = TextBox1.Text;
 24             u.note = TextBox2.Text;
 25             MemcacheHelper.AddCache("user", u,DateTime.Now .AddDays (1));
 26         }
 27 
 28 
 29 MemcacheHelper.cs文件代码:
 30 using System;
 31 using System.Collections.Generic;
 32 using System.Linq;
 33 using System.Web;
 34 using System.Data.SqlClient;
 35 using System.Data;
 36 using System.Configuration;
 37 
 38 
 39 public class SqlHelper
 40 {
 41     private static SqlConnection cn = null;
 42     private static SqlCommand cmd = null;
 43 
 44     public SqlHelper()
 45     {
 46 
 47     }
 48 
 49     /// <summary>
 50     /// 判断连接状态
 51     /// </summary>
 52     /// <returns>返回连接状态</returns>
 53     private static SqlConnection GetConn()
 54     {
 55         string ConnStr = ConfigurationManager.ConnectionStrings["HesionOA"].ToString();
 56         cn = new SqlConnection(ConnStr);
 57         if (cn.State != ConnectionState.Open)
 58         {
 59             cn.Open();
 60         }
 61         return cn;
 62     }
 63 
 64     /// <summary>
 65     /// 判断连接状态
 66     /// </summary>
 67     /// <returns>返回连接状态</returns>
 68     private static SqlConnection GetConns()
 69     {
 70         string ConnStr = ConfigurationManager.ConnectionStrings["HesionEnterprise"].ToString();
 71         cn = new SqlConnection(ConnStr);
 72         if (cn.State != ConnectionState.Open)
 73         {
 74             cn.Open();
 75         }
 76         return cn;
 77     }
 78 
 79 
 80     /// <summary>
 81     /// 判断连接状态
 82     /// </summary>
 83     /// <returns>返回连接状态</returns>
 84     private static SqlConnection GetConnSales()
 85     {
 86         string ConnStr = ConfigurationManager.ConnectionStrings["HesionSales"].ToString();
 87         cn = new SqlConnection(ConnStr);
 88         if (cn.State != ConnectionState.Open)
 89         {
 90             cn.Open();
 91         }
 92         return cn;
 93     }
 94 
 95     /// <summary>
 96     /// 获取某表的某个字段的最大值
 97     /// </summary>
 98     /// <param name="FieldName">字段名</param>
 99     /// <param name="TableName">表明</param>
100     /// <returns>返回最大值</returns>
101     public static int GetMaxID(string FieldName, string TableName)
102     {
103         string strsql = "select max(" + FieldName + ")+1 from " + TableName;
104         object obj = SqlHelper.GetSingle(strsql);
105         if (obj == null)
106         {
107             return 1;
108         }
109         else
110         {
111             return int.Parse(obj.ToString());
112         }
113     }
114     /// <summary>
115     /// 执行一条计算查询结果语句,返回查询结果(object)。
116     /// </summary>
117     /// <param name="SQLString">计算查询结果语句</param>
118     /// <returns>查询结果(object)</returns>
119     public static object GetSingle(string SQLString)
120     {
121         using (SqlCommand cmd = new SqlCommand(SQLString, GetConn()))
122         {
123             try
124             {
125                 object obj = cmd.ExecuteScalar();
126                 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
127                 {
128                     return null;
129                 }
130                 else
131                 {
132                     return obj;
133                 }
134             }
135             catch (System.Data.SqlClient.SqlException e)
136             {
137                 throw e;
138             }
139         }
140 
141     }
142 
143     /// <summary>
144     /// 带参数返回一行一列ExecuteScalar
145     /// </summary>
146     /// <param name="cmdtext">存储过程或者SQL语句</param>
147     /// <param name="para">参数数组</param>
148     /// <param name="ct">命令类型</param>
149     /// <returns>返回一行一列value</returns>
150     public static int ExecuteScalar(string cmdtext, SqlParameter[] para, CommandType ct)
151     {
152         int value;
153         try
154         {
155             cmd = new SqlCommand(cmdtext, GetConn());
156             cmd.CommandType = ct;
157             cmd.Parameters.AddRange(para);
158             value = Convert.ToInt32(cmd.ExecuteScalar());
159         }
160         catch (Exception ex)
161         {
162             throw ex;
163         }
164         finally
165         {
166             if (cn.State == ConnectionState.Open)
167             {
168                 cn.Close();
169             }
170         }
171         return value;
172     }
173 
174     /// <summary>
175     /// 带参数返回一行一列ExecuteScalar
176     /// </summary>
177     /// <param name="cmdtext">存储过程或者SQL语句</param>
178     /// <param name="para">参数数组</param>
179     /// <param name="ct">命令类型</param>
180     /// <returns>返回一行一列value</returns>
181     public static int ExecuteScalar(string cmdtext, CommandType ct)
182     {
183         int value;
184         try
185         {
186             cmd = new SqlCommand(cmdtext, GetConn());
187             cmd.CommandType = ct;
188             value = Convert.ToInt32(cmd.ExecuteScalar());
189         }
190         catch (Exception ex)
191         {
192             throw ex;
193         }
194         finally
195         {
196             if (cn.State == ConnectionState.Open)
197             {
198                 cn.Close();
199             }
200         }
201         return value;
202     }
203     /// <summary>
204     /// 执行无参的操作
205     /// </summary>
206     /// <param name="cmdtext">SQL语句或存储过程</param>
207     /// <param name="ct">CMD的类型</param>
208     /// <returns>处理后的值</returns>
209     public static int ExecuteNonQuery(string cmdtext, CommandType ct)
210     {
211         int value;
212         try
213         {
214             cmd = new SqlCommand(cmdtext, GetConn());
215             cmd.CommandType = ct;
216             value = cmd.ExecuteNonQuery() > 0 ? 1 : 0;
217         }
218         catch (Exception ex)
219         {
220             throw ex;
221         }
222         finally
223         {
224             if (cn.State == ConnectionState.Open)
225             {
226                 cn.Close();
227             }
228         }
229         return value;
230     }
231 
232     /// <summary>
233     /// 执行带参的增.删.改操作
234     /// </summary>
235     /// <param name="cmdtext">SQL语句或存储过程</param>
236     /// <param name="para">参数数组</param>
237     /// <param name="ct">CMD类型</param>
238     /// <returns>处理后的值</returns>
239     public static int ExecuteNonQuery(string cmdtext, SqlParameter[] para, CommandType ct)
240     {
241         int value;
242         using (cmd = new SqlCommand(cmdtext, GetConn()))
243         {
244             cmd.CommandType = ct;
245             cmd.Parameters.AddRange(para);
246             value = cmd.ExecuteNonQuery() > 0 ? 1 : 0;
247         }
248         return value;
249     }
250 
251     /// <summary>
252     /// 执行无参的查询 返回DataTable
253     /// </summary>
254     /// <param name="cmdtext">存储过程名称或SQL语句</param>
255     /// <param name="ct">命令类型</param>
256     /// <returns>返回DataTable</returns>
257     public static DataTable ReturnDataTable(string cmdtext, CommandType ct)
258     {
259         DataTable dt = new DataTable();
260         cmd = new SqlCommand(cmdtext, GetConn());
261         //类型
262         cmd.CommandType = ct;
263         SqlDataReader dr = null;
264         //连接池 读完自动释放Connection
265         using (dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
266         {
267             //用委托填充DataTable
268             dt.Load(dr);
269         }
270         return dt;
271     }
272 
273 
274     
275 
276         /// <summary>
277     /// 执行无参的查询 返回DataTable
278     /// </summary>
279     /// <param name="cmdtext">存储过程名称或SQL语句</param>
280     /// <param name="ct">命令类型</param>
281     /// <returns>返回DataTable</returns>
282     public static DataTable ReturnDataTableDBSales(string cmdtext, CommandType ct)
283     {
284         DataTable dt = new DataTable();
285         cmd = new SqlCommand(cmdtext, GetConnSales());
286         //类型
287         cmd.CommandType = ct;
288         SqlDataReader dr = null;
289         //连接池 读完自动释放Connection
290         using (dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
291         {
292             //用委托填充DataTable
293             dt.Load(dr);
294         }
295         return dt;
296     }
297     /// <summary>
298     /// 执行无参的查询 返回DataTable
299     /// </summary>
300     /// <param name="cmdtext">存储过程名称或SQL语句</param>
301     /// <param name="ct">命令类型</param>
302     /// <returns>返回DataTable</returns>
303     public static DataTable ReturnDataTableDB(string cmdtext, CommandType ct)
304     {
305         DataTable dt = new DataTable();
306         cmd = new SqlCommand(cmdtext, GetConns());
307         //类型
308         cmd.CommandType = ct;
309         SqlDataReader dr = null;
310         //连接池 读完自动释放Connection
311         using (dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
312         {
313             //用委托填充DataTable
314             dt.Load(dr);
315         }
316         return dt;
317     }
318 
319     
320     /// <summary>
321     /// 执行有参的查询 返回DataTable
322     /// </summary>
323     /// <param name="cmdtext">存储过程名称或SQL语句</param>
324     /// <param name="ct">命令类型</param>
325     /// <param name="para">参数数组</param>
326     /// <returns>返回DataTable</returns>
327     public static DataTable ReturnDataTable(string cmdtext, CommandType ct, SqlParameter[] para)
328     {
329         DataTable dt = new DataTable();
330         cmd = new SqlCommand(cmdtext, GetConn());
331         //类型
332         cmd.CommandType = ct;
333         //参数数组
334         cmd.Parameters.AddRange(para);
335         SqlDataReader dr = null;
336         //连接池 读完自动释放Connection
337         using (dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
338         {
339             //用委托填充DataTable
340             dt.Load(dr);
341         }
342         return dt;
343     }
344 
345     public static DataTable ReturnDataTableDB(string cmdtext, CommandType ct, SqlParameter[] para)
346     {
347         DataTable dt = new DataTable();
348         cmd = new SqlCommand(cmdtext, GetConns());
349         //类型
350         cmd.CommandType = ct;
351         //参数数组
352         cmd.Parameters.AddRange(para);
353         SqlDataReader dr = null;
354         //连接池 读完自动释放Connection
355         using (dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
356         {
357             //用委托填充DataTable
358             dt.Load(dr);
359         }
360         return dt;
361     }
362 
363     public static DataTable ReturnDataTableDBSales(string cmdtext, CommandType ct, SqlParameter[] para)
364     {
365         DataTable dt = new DataTable();
366         cmd = new SqlCommand(cmdtext, GetConnSales());
367         //类型
368         cmd.CommandType = ct;
369         //参数数组
370         cmd.Parameters.AddRange(para);
371         SqlDataReader dr = null;
372         //连接池 读完自动释放Connection
373         using (dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
374         {
375             //用委托填充DataTable
376             dt.Load(dr);
377         }
378         return dt;
379     }
380 
381     /// <summary>
382     /// 执行无参的查询 返回DataSet
383     /// </summary>
384     /// <param name="cmdtext">存储过程名称或SQL语句</param>
385     /// <param name="ct">命令类型</param>
386     /// <returns>返回DataSet</returns>
387     public static DataSet ReturnDataSet(string cmdtext, CommandType ct)
388     {
389         cmd = new SqlCommand(cmdtext, GetConn());
390         //类型
391         cmd.CommandType = ct;
392         SqlDataAdapter da = new SqlDataAdapter(cmd);
393         DataSet ds = new DataSet();
394         try
395         {
396             da.Fill(ds);
397         }
398         catch (Exception err)
399         {
400 
401             throw err;
402         }
403         finally
404         {
405             if (cn.State != ConnectionState.Closed)
406             {
407                 cn.Close();
408             }
409         }
410         return ds;
411     }
412 
413 
414 
415 
416     /// <summary>
417     /// 执行有参的查询 返回DataSet
418     /// </summary>
419     /// <param name="cmdtext">存储过程名称或SQL语句</param>
420     /// <param name="ct">命令类型</param>
421     /// <param name="para">参数数组</param>
422     /// <returns>返回DataSet</returns>
423     public static DataSet ReturnDataSet(string cmdtext, CommandType ct, SqlParameter[] para)
424     {
425         cmd = new SqlCommand(cmdtext, GetConn());
426         //类型
427         cmd.CommandType = ct;
428         //参数数组
429         cmd.Parameters.AddRange(para);
430         SqlDataAdapter da = new SqlDataAdapter(cmd);
431         DataSet ds = new DataSet();
432         try
433         {
434             da.Fill(ds);
435         }
436         catch (Exception err)
437         {
438 
439             throw err;
440         }
441         finally
442         {
443             if (cn.State != ConnectionState.Closed)
444             {
445                 cn.Close();
446             }
447         }
448         return ds;
449     }
450 
451 }
View Code

 

记录缓存(key为user),一个用来修改缓存,可是,我记录缓存的网站可以随意的存取,可是另一个网站确读不到(key为user)的值,我的2个网站都是客户端,为什么专门用来取值的网站读不到值呢?

guoguo1990的主页 guoguo1990 | 初学一级 | 园豆:4
提问于:2016-01-08 14:16
< >
分享
所有回答(2)
0

你下面代码贴错了吧,不应该是MemcacheHelper吗?怎么贴的是SqlHelper。

nike_ha | 园豆:172 (初学一级) | 2016-01-12 12:52
0

缓存配错了吧,估计,代码贴出来 看下吧

唯我独萌 | 园豆:532 (小虾三级) | 2016-01-12 14:12

代码粘错了,是这样的

using Memcached.ClientLibrary;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;

namespace SetCatch
{
    
    public class MemcacheHelper
    {
        #region 全局静态对象
        // 全局Socket连接池对象
        private static SockIOPool sockIOPool;
        public static SockIOPool CurrentPool
        {
            get
            {
                return sockIOPool;
            }
        }
        // 全局Memcached客户端对象
        private static MemcachedClient mc;
        #endregion



        public static bool MemcacheHelperInit()
        {
            try
            {
                // 初始化Memcached服务器列表
                string[] serverList = ConfigurationManager.AppSettings["Memcached.ServerList"].Split(',');
                // 初始化Socket连接池
                sockIOPool = SockIOPool.GetInstance("MemPool");
                sockIOPool.SetServers(serverList);
                sockIOPool.InitConnections = 10;
                sockIOPool.MinConnections = 1;
                sockIOPool.MaxConnections = 10;
                sockIOPool.Initialize();
                // 初始化Memcached客户端
                mc = new MemcachedClient();
                mc.PoolName = "MemPool";
                mc.EnableCompression = false;
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 判断pkey关键字是否在Pmc中
        /// </summary>
        /// <param name="pMC"></param>
        /// <param name="pKey"></param>
        /// <returns></returns>
        public static bool IsCache(string pKey)
        {
            if (MemcacheHelperInit())
            {
                if (mc.KeyExists(pKey))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删掉Memcache 数据
        /// </summary>
        /// <param name="key"> </param>
        /// <returns></returns>
        public static bool RemoveCache(string pKey)
        {
            if (MemcacheHelperInit())
            {
                if (!mc.KeyExists(pKey))
                {
                    return false;
                }
                else
                {
                    return mc.Delete(pKey);
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Set-新增或修改
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns>是否成功</returns>
        public static bool AddCache(string key, object value)
        {
            if (MemcacheHelperInit())
            {
                if (!mc.KeyExists(key))
                {
                    return mc.Add(key, value);
                }
                else
                {
                    return mc.Set(key, value);
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Set-新增或修改
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expiry">过期时间</param>
        /// <returns>是否成功</returns>
        public static bool AddCache(string key, object value, DateTime expiry)
        {
            if (MemcacheHelperInit())
            {
                if (!mc.KeyExists(key))
                {
                    return mc.Add(key, value, expiry);
                }
                else
                {
                    return mc.Set(key, value, expiry);
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 根据单个key值获取Memcache 数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static object GetCache(string key)
        {
            if (MemcacheHelperInit())
            {
                if (!mc.KeyExists(key))
                {
                    return null;
                }
                else
                {
                    return mc.Get(key);
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 根据多个key值获取Memcache 数据
        /// </summary>
        /// <param name="key"> </param>
        /// <returns></returns>
        public static Dictionary<string, object> GetCache(string[] keys)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            if (MemcacheHelperInit())
            {
                foreach (string key in keys)
                {
                    object obj = mc.Get(key);
                    if (!dic.ContainsKey(key) && obj != null)
                        dic.Add(key, obj);
                }
                return dic;
            }
            else
            {
                return null;
            }
        }
    }
}
支持(0) 反对(0) guoguo1990 | 园豆:4 (初学一级) | 2016-01-13 13:05

2个网站用的Helper是一模一样的

支持(0) 反对(0) guoguo1990 | 园豆:4 (初学一级) | 2016-01-13 13:06

@guoguo1990: 把属性的值 改下,转到定义看下,还有那些属性

支持(0) 反对(0) 唯我独萌 | 园豆:532 (小虾三级) | 2016-01-13 13:21

应该怎么改呢,属性和方法都在这个页面呢

支持(0) 反对(0) guoguo1990 | 园豆:4 (初学一级) | 2016-01-13 13:26

@guoguo1990: 在本地应该可以 写个demo调试方法,看是否进入了。

 sockIOPool = SockIOPool.GetInstance("MemPool");
                sockIOPool.SetServers(serverList);
                sockIOPool.InitConnections = 10;
                sockIOPool.MinConnections = 1;
                sockIOPool.MaxConnections = 10;

的值改大点,在看sockIOPool 里面的属性,还有什么

支持(0) 反对(0) 唯我独萌 | 园豆:532 (小虾三级) | 2016-01-13 13:28

@背叛的冲刷:没有其他的sockIOPool的属性了 ,我把值都改成20 了还不成,

获取缓存Demo:
  public void GetCatch()
        {
            Label1.Visible = false;
            string key = "user";//key值
            object obj = new object();
            if (MemcacheHelper.IsCache(key))
            {
                obj = MemcacheHelper.GetCache(key);
                Users u = (obj) as Users;
                TextBox1.Text = u.name;
                TextBox2.Text = u.note;
            }
            else
            {
                Label1.Visible = true;
            }
        }

设置缓存Demo

  Users u = new Users();
            u.name = TextBox1.Text;
            u.note = TextBox2.Text;
            MemcacheHelper.AddCache("user", u,DateTime.Now .AddDays (1));
支持(0) 反对(0) guoguo1990 | 园豆:4 (初学一级) | 2016-01-13 13:36

@guoguo1990: http://blog.csdn.net/anialy/article/details/9185337

文章看下吧,大体上属性差不多

支持(0) 反对(0) 唯我独萌 | 园豆:532 (小虾三级) | 2016-01-13 13:38

@背叛的冲刷: 还有别的办法吗,实在不知道是什么原因了,我通过远程都能访问到呢

支持(0) 反对(0) guoguo1990 | 园豆:4 (初学一级) | 2016-01-21 15:06

@guoguo1990: 估计应该是对象 不一致的问题,可以创建个对 缓存服务器的接口访问地址引用

支持(0) 反对(0) 唯我独萌 | 园豆:532 (小虾三级) | 2016-01-21 16:47

@背叛的冲刷: 你的意思是,我应该用单例模式吗?不过不是的话,就算调用一个 MemcacheHelper每次还是new MemcachedClient()

支持(0) 反对(0) guoguo1990 | 园豆:4 (初学一级) | 2016-01-21 17:05
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册