memcached-client

郭凯
2023-12-01
/**
	 * Deletes an object from cache given cache key, a delete time, and an optional hashcode.
	 *
	 *  The item is immediately made non retrievable.<br/>
	 *  Keep in mind {@link #add(String, Object) add} and {@link #replace(String, Object) replace}<br/>
	 *  will fail when used with the same key will fail, until the server reaches the<br/>
	 *  specified time. However, {@link #set(String, Object) set} will succeed,<br/>
	 *  and the new value will not be deleted.
	 *
	 * @param key the key to be removed
	 * @param hashCode if not null, then the int hashcode to use
	 * @param expiry when to expire the record.
	 * @return <code>true</code>, if the data was deleted successfully
	 */
	public boolean delete( String key, Integer hashCode, Date expiry ) {

		if ( key == null ) {
			log.error( "null value for key passed to delete()" );
			return false;
		}

		try {
			key = sanitizeKey( key );
		}
		catch ( UnsupportedEncodingException e ) {

			// if we have an errorHandler, use its hook
			if ( errorHandler != null )
				errorHandler.handleErrorOnDelete( this, e, key );

			log.error( "failed to sanitize your key!", e );
			return false;
		}

		// get SockIO obj from hash or from key
		SockIOPool.SockIO sock = pool.getSock( key, hashCode );

		// return false if unable to get SockIO obj
		if ( sock == null ) {
			if ( errorHandler != null )
				errorHandler.handleErrorOnDelete( this, new IOException( "no socket to server available" ), key );
			return false;
		}

		// build command
		StringBuilder command = new StringBuilder( "delete " ).append( key );
		if ( expiry != null )
			command.append( " " + expiry.getTime() / 1000 );

		command.append( "\r\n" );

		try {
			sock.write( command.toString().getBytes() );
			sock.flush();

			// if we get appropriate response back, then we return true
			String line = sock.readLine();
			if ( DELETED.equals( line ) ) {
				if ( log.isInfoEnabled() )
					log.info( "++++ deletion of key: " + key + " from cache was a success" );

				// return sock to pool and bail here
				sock.close();
				sock = null;
				return true;
			}
			else if ( NOTFOUND.equals( line ) ) {
				if ( log.isInfoEnabled() )
					log.info( "++++ deletion of key: " + key + " from cache failed as the key was not found" );
			}
			else {
				log.error( "++++ error deleting key: " + key );
				log.error( "++++ server response: " + line );
			}
		}
		catch ( IOException e ) {

			// if we have an errorHandler, use its hook
			if ( errorHandler != null )
				errorHandler.handleErrorOnDelete( this, e, key );

			// exception thrown
			log.error( "++++ exception thrown while writing bytes to server on delete" );
			log.error( e.getMessage(), e );

			try {
				sock.trueClose();
			}
			catch ( IOException ioe ) {
				log.error( "++++ failed to close socket : " + sock.toString() );
			}

			sock = null;
		}

		if ( sock != null ) {
			sock.close();
			sock = null;
		}

		return false;
	}
    

 类似资料: