Пример #1
0
		public object GetLock(CacheKey key) 
		{
			int controllerId = HashCodeProvider.GetIdentityHashCode(_controller);
			int keyHash = key.GetHashCode();
			int lockKey = 29 * controllerId + keyHash;
			object lok =_lockMap[lockKey];
			if (lok == null) 
			{
				lok = lockKey; //might as well use the same object
				_lockMap[lockKey] = lok;
			}
			return lok;
		}
Пример #2
0
		/// <summary>
		/// Adds an item with the specified key and value into cached data.
		/// Gets a cached object with the specified key.
		/// </summary>
		/// <value>The cached object or <c>null</c></value>
		/// <remarks>
		/// A side effect of this method is that is may clear the cache
		/// if it has not been cleared in the flushInterval.
		/// </remarks> 
		public object this [CacheKey key] 
		{
			get
			{
				lock(this) 
				{
					if (_lastFlush != NO_FLUSH_INTERVAL
						&& (DateTime.Now.Ticks - _lastFlush > _flushInterval.Interval)) 
					{
						Flush();
					}
				}

				object value = null;
				lock (GetLock(key)) 
				{
					value = _controller[key];
				}

				if(_isSerializable && !_isReadOnly &&
					(value != NULL_OBJECT && value != null))
				{
					try
					{
						MemoryStream stream = new MemoryStream((byte[]) value);
						stream.Position = 0;
						BinaryFormatter formatter = new BinaryFormatter();
						value = formatter.Deserialize( stream );
					}
					catch(Exception ex)
					{
						throw new IbatisException("Error caching serializable object.  Be sure you're not attempting to use " +
							"a serialized cache for an object that may be taking advantage of lazy loading.  Cause: "+ex.Message, ex);
					}
				}

				lock(_statLock) 
				{
					_requests++;
					if (value != null) 
					{
						_hits++;
					}
				}

                if (_logger.IsDebugEnabled)
                {
                    if (value != null)
                    {
                        _logger.Debug(String.Format("Retrieved cached object '{0}' using key '{1}' ", value, key));
                    }
                    else
                    {
                        _logger.Debug(String.Format("Cache miss using key '{0}' ", key));
                    }
                }
				return value;
			}
			set
			{
				if (null == value) {value = NULL_OBJECT;}
				if(_isSerializable && !_isReadOnly && value != NULL_OBJECT)
				{
					try
					{
						MemoryStream stream = new MemoryStream();
						BinaryFormatter formatter = new BinaryFormatter();
						formatter.Serialize(stream, value);
						value = stream.ToArray();
					}
					catch(Exception ex)
					{
						throw new IbatisException("Error caching serializable object. Cause: "+ex.Message, ex);
					}
				}
				_controller[key] = value;
                if (_logger.IsDebugEnabled)
                {
                    _logger.Debug(String.Format("Cache object '{0}' using key '{1}' ", value, key));
                }
			}
		}