/** 存入一个对象 */
  private boolean _set(String key, Object value) {
    // mc1.delete(key);
    // mc2.delete(key);
    boolean ret = false;
    Future<Boolean> f = mc1.set(key, expHour * 60 * 60, value);
    Future<Boolean> f2 = mc2.set(key, expHour * 60 * 60, value);
    try {
      boolean fs1 = f.get(opTimeout, TimeUnit.SECONDS);
      boolean fs2 = f2.get(opTimeout, TimeUnit.SECONDS);
      ret = fs1 || fs2;

      if (!fs1) {
        log.info(
            "[FAIL]CACHE SET FAIL:server1 set failed: "
                + "Key="
                + key
                + "\tValue="
                + value.toString());
      } else if (!fs2) {
        log.info(
            "[FAIL]CACHE SET FAIL:server2 set failed: "
                + "Key="
                + key
                + "\tValue="
                + value.toString());
      }
    } catch (TimeoutException e) {
      // Since we don't need this, go ahead and cancel the
      // operation. This
      // is not strictly necessary, but it'll save some work on
      // the server.
      log.info("[FAIL]time out when getting objects from cache server2...");
      f.cancel(false);
      f2.cancel(false);
      // Do other timeout related stuff
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      log.error("[ERROR]exception when setting fengchao cache - thread been interrupted...", e);
      f.cancel(false);
      f2.cancel(false);
    } catch (ExecutionException e) {
      // TODO Auto-generated catch block
      log.error(
          "[ERROR]exception when setting fengchao cache - exception when getting status...", e);
      f.cancel(false);
      f2.cancel(false);
    } catch (Exception e) {
      log.error("[ERROR]exception when setting fengchao cache - other exceptions...", e);
      f.cancel(false);
      f2.cancel(false);
    }

    if (value != null) {
      log.info("MemCacheServiceImpl.set,key=" + key + ",value=" + value.getClass());
    } else {
      log.info("MemCacheServiceImpl.set,key=" + key + ",value=null");
    }
    return ret;
  }
Exemplo n.º 2
0
  public V put(K key, V value) {
    memcachedClient.set(key.toString(), NOT_EXPIRE, value);

    // Key index update
    if (!keySet().contains(key)) {
      String index = (String) get(name + KEYS_LOCATION);
      index = index + key.toString() + KEY_SEPARATOR;
      memcachedClient.set(name + KEYS_LOCATION, NOT_EXPIRE, index);
    }

    return value;
  }
Exemplo n.º 3
0
 public void clear() {
   for (Object key : keySet()) {
     remove((K) key);
   }
   // Removing the index
   memcachedClient.set(name + KEYS_LOCATION, NOT_EXPIRE, "");
 }
Exemplo n.º 4
0
 @Override
 public void set(String key, String value) {
   if (StringTools.isEmpty(key) || !enable) {
     return;
   }
   client.set(buildKey(key), 0, value);
 }
  @Override
  public boolean set(String key, Object value, int exp) {
    // mc1.delete(key);
    // mc2.delete(key);
    boolean ret = false;
    Future<Boolean> f = mc1.set(key, exp, value);
    Future<Boolean> f2 = mc2.set(key, exp, value);

    try {
      boolean fs1 = f.get(opTimeout, TimeUnit.SECONDS);
      boolean fs2 = f2.get(opTimeout, TimeUnit.SECONDS);
      ret = fs1 || fs2;

      if (!fs1) {
        log.info(
            "[FAIL]CACHE SET FAIL:server1 set failed: "
                + "Key="
                + key
                + ",Value="
                + value.toString());
      } else if (!fs2) {
        log.info(
            "[FAIL]CACHE SET FAIL:server2 set failed: "
                + "Key="
                + key
                + ",Value="
                + value.toString());
      }
    } catch (Exception e) {
      if (!"LOGIN_IP".equalsIgnoreCase(key)) {
        log.info("MemCacheServiceImpl.set,key=" + key + ",value=" + value + ",Exception");
      }
      e.printStackTrace();
      f.cancel(false);
      f2.cancel(false);
    }
    if (value != null) {
      if (!"LOGIN_IP".equalsIgnoreCase(key)) {
        log.info("MemCacheServiceImpl.set,key=" + key + ",value=" + value.getClass());
      }
    } else {
      if (!"LOGIN_IP".equalsIgnoreCase(key)) {
        log.info("MemCacheServiceImpl.set,key=" + key + ",value=null");
      }
    }
    return ret;
  }
  /**
   * This is an example based on http://www.mongodb.org/display/DOCS/Java+Tutorial to see if things
   * work.
   */
  @Test
  public void testSample() throws Exception {

    // perform operations
    jmemcache.set("key", 5, "value");
    // getting the key value
    assertEquals("value", jmemcache.get("key"));
  }
 public static void setSpyCache(
     net.spy.memcached.MemcachedClient mcc, String key, int exp, Object value) {
   OperationFuture<Boolean> set = mcc.set(key, 0, key);
   try {
     if (!set.get(10, TimeUnit.SECONDS)) System.err.println(key + " set not ok");
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  public static void main(String[] args) throws IOException {

    MemcachedClient c = new MemcachedClient(new InetSocketAddress("localhost", 11211));

    // Store a value (async) for one hour
    c.set("name", 3600, "咖啡兔");
    // Retrieve a value.
    Object myObject = c.get("name");
    System.out.println(myObject);
  }
Exemplo n.º 9
0
 @Override
 public void set(String key, String value, int exprieSecond) {
   if (StringTools.isEmpty(key) || !enable) {
     return;
   }
   if (exprieSecond < 0) {
     exprieSecond = 0;
   }
   client.set(buildKey(key), exprieSecond, value);
 }
Exemplo n.º 10
0
  public V remove(Object key) {
    V myObj = (V) get(key);
    memcachedClient.delete(key.toString());

    // Key index update
    String index = (String) get(name + KEYS_LOCATION);
    index = index.replace(key.toString() + KEY_SEPARATOR, "");
    memcachedClient.set(name + KEYS_LOCATION, NOT_EXPIRE, index);

    return myObj;
  }
  /**
   * Is invoked for the backup of a non-sticky session that was not accessed for the current
   * request.
   */
  protected void onBackupWithoutLoadedSession(
      @Nonnull final String sessionId,
      @Nonnull final String requestId,
      @Nonnull final BackupSessionService backupSessionService) {

    if (!_sessionIdFormat.isValid(sessionId)) {
      return;
    }

    try {

      final long start = System.currentTimeMillis();

      final String validityKey = _sessionIdFormat.createValidityInfoKeyName(sessionId);
      final SessionValidityInfo validityInfo = loadSessionValidityInfoForValidityKey(validityKey);
      if (validityInfo == null) {
        _log.warn("Found no validity info for session id " + sessionId);
        return;
      }

      final int maxInactiveInterval = validityInfo.getMaxInactiveInterval();
      final byte[] validityData =
          encode(maxInactiveInterval, System.currentTimeMillis(), System.currentTimeMillis());
      // fix for #88, along with the change in session.getMemcachedExpirationTimeToSet
      final int expiration = maxInactiveInterval <= 0 ? 0 : maxInactiveInterval;
      final Future<Boolean> validityResult =
          _memcached.set(validityKey, toMemcachedExpiration(expiration), validityData);
      if (!_manager.isSessionBackupAsync()) {
        validityResult.get(_manager.getSessionBackupTimeout(), TimeUnit.MILLISECONDS);
      }

      /*
       * - ping session
       * - ping session backup
       * - save validity backup
       */
      final Callable<?> backupSessionTask =
          new OnBackupWithoutLoadedSessionTask(
              sessionId, _storeSecondaryBackup, validityKey, validityData, maxInactiveInterval);
      _executor.submit(backupSessionTask);

      if (_log.isDebugEnabled()) {
        _log.debug("Stored session validity info for session " + sessionId);
      }

      _stats.registerSince(NON_STICKY_ON_BACKUP_WITHOUT_LOADED_SESSION, start);

    } catch (final Throwable e) {
      _log.warn("An error when trying to load/update validity info.", e);
    }
  }
Exemplo n.º 12
0
  @Test
  public void getWrongCachedObject() throws IOException {
    MemcachedConnection.connect(host, port);
    MemcachedClient client = MemcachedConnection.getConnection();

    // set in memcached
    String key = UUID.randomUUID().toString();
    String content = "slok_" + UUID.randomUUID().toString();
    int seconds = 2;
    client.set(key, seconds, content);

    // get from memcached and check
    String result = (String) client.get("notAKey");
    assertNull(result);
  }
Exemplo n.º 13
0
  @Test
  public void getExpiredCachedObject() throws IOException, InterruptedException {
    MemcachedConnection.connect(host, port);
    MemcachedClient client = MemcachedConnection.getConnection();

    // set in memcached
    String key = UUID.randomUUID().toString();
    String content = "slok_" + UUID.randomUUID().toString();
    int seconds = 1;
    client.set(key, seconds, content);

    Thread.sleep(1001);

    // get from memcached and check
    String result = (String) client.get(key);
    assertNull(result);
  }
  public static void main(String[] args) throws Exception {
    final MemcachedClient db = new MemcachedClient(AddrUtil.getAddresses(args[0]));
    final Transcoder<Object> transcoder =
        new Transcoder<Object>() {
          public CachedData encode(Object data) {
            return new CachedData(0, (byte[]) data, getMaxSize());
          }

          public Object decode(CachedData cachedData) {
            return cachedData.getData();
          }

          public boolean asyncDecode(CachedData arg0) {
            return false;
          }

          public int getMaxSize() {
            return CachedData.MAX_SIZE;
          }
        };
    final String key = "key";
    final byte[] value = new byte[128];
    value[0] = 1;
    value[1] = 2;
    value[2] = 3;
    db.set(key, 0, value).get();
    Runnable task =
        new Runnable() {
          public void run() {
            try {
              assertArrayEquals(value, (byte[]) db.asyncGet(key, transcoder).get());
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };
    for (int c : new int[] {1, 10, 100, 200, 300}) {
      System.out.println(c + ":" + (new Benchmark(c, 10000).run(task)) + "ms");
    }
    db.shutdown();
  }
Exemplo n.º 15
0
  public boolean remember(String key, Serializable object) {

    if (memcache != null) {

      log.debug("Storing object as {}", key);
      OperationFuture<Boolean> future = null;

      if (memcache.get(key) == null) {
        log.debug("using memcache.add(..)");
        future = memcache.add(key, expireTime, object);
      } else {
        log.debug("Using memcache.set(..)");
        future = memcache.set(key, expireTime, object);
      }

      try {
        return future.get(1, TimeUnit.SECONDS);
      } catch (Exception e) {
        log.error("Failed to store value for key {}: {}", key, e.getMessage());
      }
    }

    return false;
  }
Exemplo n.º 16
0
  public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    String configEndpoint = "localhost";
    Integer clusterPort = 11211;

    MemcachedClient client =
        new MemcachedClient(new InetSocketAddress(configEndpoint, clusterPort));
    // DefaultConnectionFactory cf=new DefaultConnectionFactory();
    // The client will connect to the other cache nodes automatically

    // Store a data item for an hour.  The client will decide which cache host will store this item.
    // Store a value (async) for one hour
    UserProfile set = new UserProfile();
    set.setEmail("myemail");
    System.out.println(client.set("someKey", 3600, set));
    // Retrieve a value (synchronously).
    // Object myObject=client.get("someKey");
    // client.set("Key1111", 10, "This is the data value");
    // System.out.println("Value is "+client.get("*****@*****.**").toString());
    Object obj = client.get("someKey");
    UserProfile up = (UserProfile) obj;
    System.out.println("Value is " + up.getEmail());
    client.shutdown();
  }
Exemplo n.º 17
0
 @Override
 public void put(String key, V value) {
   memcached.set(key, 0, value);
 }
Exemplo n.º 18
0
 public void initialize() throws Exception {
   // Key index support
   if (null == get(name + KEYS_LOCATION)) {
     memcachedClient.set(name + KEYS_LOCATION, NOT_EXPIRE, "");
   }
 }
Exemplo n.º 19
0
 @Test
 public void saveTest() throws InterruptedException, ExecutionException {
   OperationFuture<Boolean> valFuture = client.set("Test_Key", 200, "Test Value");
   assertEquals(true, valFuture.get().booleanValue());
 }
Exemplo n.º 20
0
 @Override
 public void set(String key, Object value, int expiration, String category) {
   writeClient.set(key, expiration, value);
 }
  /**
   * Is invoked after the backup of the session is initiated, it's represented by the provided
   * backupResult. The requestId is identifying the request.
   */
  protected void onAfterBackupSession(
      @Nonnull final MemcachedBackupSession session,
      final boolean backupWasForced,
      @Nonnull final Future<BackupResult> result,
      @Nonnull final String requestId,
      @Nonnull final BackupSessionService backupSessionService) {

    if (!_sessionIdFormat.isValid(session.getIdInternal())) {
      return;
    }

    try {

      final long start = System.currentTimeMillis();

      final int maxInactiveInterval = session.getMaxInactiveInterval();
      final byte[] validityData =
          encode(
              maxInactiveInterval,
              session.getLastAccessedTimeInternal(),
              session.getThisAccessedTimeInternal());
      final String validityKey =
          _sessionIdFormat.createValidityInfoKeyName(session.getIdInternal());
      // fix for #88, along with the change in session.getMemcachedExpirationTimeToSet
      final int expiration = maxInactiveInterval <= 0 ? 0 : maxInactiveInterval;
      final Future<Boolean> validityResult =
          _memcached.set(validityKey, toMemcachedExpiration(expiration), validityData);
      if (!_manager.isSessionBackupAsync()) {
        // TODO: together with session backup wait not longer than sessionBackupTimeout.
        // Details: Now/here we're waiting the whole session backup timeout, even if (perhaps) some
        // time
        // was spent before when waiting for session backup result.
        // For sync session backup it would be better to set both the session data and
        // validity info and afterwards wait for both results (but in sum no longer than
        // sessionBackupTimeout)
        validityResult.get(_manager.getSessionBackupTimeout(), TimeUnit.MILLISECONDS);
      }
      if (_log.isDebugEnabled()) {
        _log.debug("Stored session validity info for session " + session.getIdInternal());
      }

      /* The following task are performed outside of the request thread (includes waiting for the backup result):
       * - ping session if the backup was skipped (depends on the backup result)
       * - save secondary session backup if session was modified (backup not skipped)
       * - ping secondary session backup if the backup was skipped
       * - save secondary validity backup
       */
      final boolean pingSessionIfBackupWasSkipped = !backupWasForced;
      final boolean performAsyncTasks = pingSessionIfBackupWasSkipped || _storeSecondaryBackup;

      if (performAsyncTasks) {
        final Callable<?> backupSessionTask =
            new OnAfterBackupSessionTask(
                session,
                result,
                pingSessionIfBackupWasSkipped,
                backupSessionService,
                _storeSecondaryBackup,
                validityKey,
                validityData);
        _executor.submit(backupSessionTask);
      }

      _stats.registerSince(NON_STICKY_AFTER_BACKUP, start);

    } catch (final Throwable e) {
      _log.warn("An error occurred during onAfterBackupSession.", e);
    }
  }
Exemplo n.º 22
0
 @Test
 public void getTest() {
   client.set("Test_Key", 200, "Test Value");
   String valString = (String) client.get("Test_Key");
   assertEquals(valString, "Test Value");
 }
 public static OperationFuture<Boolean> setSpyAsynCache(
     net.spy.memcached.MemcachedClient mcc, String key, int exp, Object value) {
   return mcc.set(key, 0, key);
 }
Exemplo n.º 24
0
 @Override
 public void set(String key, Object value, int expiration) {
   client.set(key, expiration, value);
 }