示例#1
0
  @POST
  @Path("action")
  public String action(
      @FormParam("element_1") double n1,
      @FormParam("element_2") double n2,
      @FormParam("element_3") String s) {
    try {
      MemcachedClient client = MccFactory.getConst("localhost").getMemcachedClient();
      JsonObject innerObject = new JsonObject();
      innerObject.addProperty("key", s);
      innerObject.addProperty("firstNum", n1);
      innerObject.addProperty("secondNum", n2);

      client.add(s, 30000, innerObject.toString());
      String keys = (String) client.get("mykeys");
      keys = (keys == null) ? "" : keys;
      keys += s + "/";
      client.replace("mykeys", 30000, keys);
    } catch (Exception e) {
      e.printStackTrace();
      return getStringStackTrace(e);
    }

    return "String: " + s + ". First number = " + n1 + ", Second number = " + n2;
  }
  /** 存入一个对象 */
  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;
  }
  /**
   * 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"));
  }
示例#4
0
  /**
   * @param args
   * @throws IOException
   * @throws URISyntaxException
   */
  public static void main(String[] args) throws IOException, URISyntaxException {
    // ApplicationContext ctx = new GenericXmlApplicationContext("applicationContext.xml");
    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    MemcachedClient memcachedClient = ctx.getBean(MemcachedClient.class);

    memcachedClient.add("testSpring", 0, "testDataSpring");
    System.out.println(memcachedClient.get("testSpring"));
    memcachedClient.shutdown();
  }
  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);
  }
示例#6
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;
  }
示例#7
0
 @GET
 @Path("get")
 public String get(@QueryParam("key") String key) {
   try {
     MemcachedClient client = MccFactory.getConst("localhost").getMemcachedClient();
     String res = (String) client.get(key);
     return (res != null) ? res : "No data found for " + key;
   } catch (Exception e) {
     e.printStackTrace();
     return getStringStackTrace(e);
   }
 }
示例#8
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;
  }
  /** Invoked after a non-sticky session is removed from memcached. */
  protected void onAfterDeleteFromMemcached(@Nonnull final String sessionId) {
    final long start = System.currentTimeMillis();

    final String validityInfoKey = _sessionIdFormat.createValidityInfoKeyName(sessionId);
    _memcached.delete(validityInfoKey);

    if (_storeSecondaryBackup) {
      _memcached.delete(_sessionIdFormat.createBackupKey(sessionId));
      _memcached.delete(_sessionIdFormat.createBackupKey(validityInfoKey));
    }

    _stats.registerSince(NON_STICKY_AFTER_DELETE_FROM_MEMCACHED, start);
  }
  @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);
  }
示例#11
0
 @Override
 public void set(String key, String value) {
   if (StringTools.isEmpty(key) || !enable) {
     return;
   }
   client.set(buildKey(key), 0, value);
 }
示例#12
0
 public void clear() {
   for (Object key : keySet()) {
     remove((K) key);
   }
   // Removing the index
   memcachedClient.set(name + KEYS_LOCATION, NOT_EXPIRE, "");
 }
示例#13
0
 @Override
 public void del(String key) {
   if (StringTools.isEmpty(key) || !enable) {
     return;
   }
   client.delete(buildKey(key));
 }
  @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;
  }
示例#15
0
  /*
   * (non-Javadoc)
   * @see cacher.memcached.GetStrategy#getBulk(java.util.List)
   */
  @Override
  public Map<String, Object> getBulk(MemcachedClient client, List<String> keys) {
    if (keys == null || keys.isEmpty()) {
      return null;
    }

    return client.getBulk(keys);
  }
示例#16
0
  /*
   * (non-Javadoc)
   * @see cacher.memcached.GetStrategy#get(java.lang.String)
   */
  @Override
  public Object get(MemcachedClient client, String key) {
    if (key == null) {
      return null;
    }

    return client.get(key);
  }
  @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);
  }
示例#18
0
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    /* Get Session */
    HttpSession s = req.getSession(true);
    /* Make sure user is logged in */
    if (s.getAttribute("login") == null || (String) s.getAttribute("login") != "go") {
      req.getRequestDispatcher("login.jsp").forward(req, res);
    }

    try {
      String dbuser = this.getServletContext().getInitParameter("dbuser");
      String dbpassword = this.getServletContext().getInitParameter("dbpassword");

      Class.forName("com.mysql.jdbc.Driver");
      Connection conn =
          DriverManager.getConnection("jdbc:mysql://localhost/project", dbuser, dbpassword);

      Statement stmt = conn.createStatement();
      stmt.execute(
          "INSERT INTO songs VALUES(null, '"
              + req.getParameter("song_name")
              + "', '"
              + req.getParameter("artist")
              + "', '"
              + req.getParameter("album")
              + "', '"
              + req.getParameter("genre")
              + "', 0)");

      stmt.close();
      conn.close();

      // delete memcache since new song is now added
      MemcachedClient c = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
      c.delete("master");

      req.getRequestDispatcher("add_song_success.jsp").forward(req, res);

    } catch (Exception e) {
      out.println(e.getMessage());
    }
  }
示例#19
0
  @DELETE
  @Path("delete")
  public String delete(@QueryParam("key") String key) {
    try {
      MemcachedClient client = MccFactory.getConst("localhost").getMemcachedClient();
      String keys = (String) client.get("mykeys");
      keys = (keys == null) ? "" : keys;
      keys = keys.replace(key + "/", "");
      client.replace("mykeys", 30000, keys);
      client.delete(key);
    } catch (Exception e) {
      e.printStackTrace();
      return getStringStackTrace(e);
    }

    return "Removed value at " + key;
  }
  /**
   * 获取一个对象
   *
   * @throws ExecutionException
   * @throws InterruptedException
   */
  private Object _get(String key) {
    // TODO Auto-generated method stub
    // log.info("[ACCESS] begin to get info from cache...");
    Object myObj = null;
    try {
      Future<Object> f = mc1.asyncGet(key);
      try {
        myObj = f.get(opTimeout, TimeUnit.SECONDS);
      } catch (TimeoutException e) {
        e.printStackTrace();
        f.cancel(false);
      } catch (InterruptedException e) {
        e.printStackTrace();
        f.cancel(false);
      } catch (ExecutionException e) {
        e.printStackTrace();
        f.cancel(false);
      }

      if (myObj == null) {
        Future<Object> f2 = mc2.asyncGet(key);
        try {
          myObj = f2.get(opTimeout, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
          e.printStackTrace();
          f2.cancel(false);
        } catch (InterruptedException e) {
          e.printStackTrace();
          f2.cancel(false);
        } catch (ExecutionException e) {
          e.printStackTrace();
          f2.cancel(false);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (myObj != null) {
      // log.info("MemCacheServiceImpl._get,key=" + key + ",object="
      // + myObj.getClass());
    } else {
      // log.info("MemCacheServiceImpl._get,key=" + key + ",object=null");
    }
    return myObj;
  }
 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();
   }
 }
  /**
   * 移除一个对象
   *
   * @see
   * @param key
   * @param value
   * @return
   * @author futuremining
   * @date 2009-1-12
   * @version 1.0.0
   */
  @Override
  public boolean remove(String key) {
    boolean ret = false;

    Future<Boolean> f = mc1.delete(key);
    Future<Boolean> f2 = mc2.delete(key);

    try {
      ret = f.get(opTimeout, TimeUnit.SECONDS) && f2.get(opTimeout, TimeUnit.SECONDS); // !!
      // 该行的判断只限于2台不同的memcached服务器
    } 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 deleting fengchao cache - thread been interrupted...", e);
      f.cancel(false);
      f2.cancel(false);
      ret = false;
    } catch (ExecutionException e) {
      // TODO Auto-generated catch block
      log.error(
          "[ERROR]exception when deleting fengchao cache - exception when getting status...", e);
      f.cancel(false);
      f2.cancel(false);
      ret = false;
    } catch (Exception e) {
      log.error("[ERROR]exception when deleting fengchao cache - other exceptions...", e);
      f.cancel(false);
      f2.cancel(false);
      ret = false;
    }

    log.info("[REMOVE]" + ret + "\tKey=" + key);

    return ret; // 如果配了相同的,即使 remove成功
    // ,也会返回false,因此此返回值有意义仅当配置两台不同memcached服务器
  }
 @AfterMethod
 public void release() {
   try {
     memcachedServer.stop();
     TestingUtil.killCacheManagers(cacheManager);
     memcachedClient.shutdown();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
示例#24
0
 public void finish() {
   try {
     if (memcache != null) {
       log.info("Shutting down memcache {}", memcache);
       memcache.shutdown(1, TimeUnit.SECONDS);
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
示例#25
0
 @Override
 public boolean add(String key, String value, int exprieSecond) {
   if (StringTools.isEmpty(key) || !enable) {
     return false;
   }
   if (exprieSecond < 0) {
     exprieSecond = 0;
   }
   return client.add(buildKey(key), exprieSecond, value).getStatus().isSuccess();
 }
示例#26
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);
 }
示例#27
0
 @SuppressWarnings("unchecked")
 @Override
 public <T> T get(String key, String category, boolean timeoutAware) {
   Future<Object> future = readClient.asyncGet(key);
   try {
     // use timeout to eliminate memcachedb servers' crash
     return (T) future.get(timeout, TimeUnit.MILLISECONDS);
   } catch (Exception e) {
     return null;
   }
 }
示例#28
0
  @GET
  @Path("list")
  public String list() {
    try {
      String result = "";
      MemcachedClient client = MccFactory.getConst("localhost").getMemcachedClient();
      String s = (String) client.get("mykeys");

      String[] keys = s.split("/");
      for (String key : keys) {
        if (key == null || key.length() < 1) continue;
        String ss = (String) client.get(key);
        if (ss != null) result += key + " " + ss + "<br/>";
      }
      return (result.length() > 0) ? result : "No data found";
    } catch (Exception e) {
      e.printStackTrace();
      return getStringStackTrace(e);
    }
  }
  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();
  }
示例#30
0
 /* (non-Javadoc)
  * @see com.dianping.cache.core.CacheClient#getBulk(java.util.Collection, java.util.Map, boolean)
  */
 @SuppressWarnings("unchecked")
 @Override
 public <T> Map<String, T> getBulk(
     Collection<String> keys, Map<String, String> categories, boolean timeoutAware) {
   Future<Map<String, Object>> future = readClient.asyncGetBulk(keys);
   try {
     // use timeout to eliminate memcachedb servers' crash
     return (Map<String, T>) future.get(timeout, TimeUnit.MILLISECONDS);
   } catch (Exception e) {
     return null;
   }
 }