/**
   * @param concurrency Concurrency.
   * @param isolation Isolation.
   * @throws GridException If test failed.
   */
  private void checkTransactionTimeout(
      GridCacheTxConcurrency concurrency, GridCacheTxIsolation isolation) throws Exception {

    boolean wasEx = false;

    GridCacheTx tx = null;

    try {
      GridCache<Integer, String> cache = grid.cache(null);

      tx = cache.txStart(concurrency, isolation, 50, 0);

      cache.put(1, "1");

      Thread.sleep(100);

      cache.put(1, "2");

      tx.commit();
    } catch (GridCacheTxOptimisticException e) {
      info("Received expected optimistic exception: " + e.getMessage());

      wasEx = true;

      tx.rollback();
    } catch (GridCacheTxTimeoutException e) {
      info("Received expected timeout exception: " + e.getMessage());

      wasEx = true;

      tx.rollback();
    }

    assert wasEx;
  }
  /** @throws Exception If failed. */
  public void testInvalidateFlag() throws Exception {
    GridEx g0 = grid(0);

    GridCache<String, String> cache = g0.cache(PARTITIONED_CACHE_NAME);

    String key = null;

    for (int i = 0; i < 10_000; i++) {
      if (!cache.affinity().isPrimaryOrBackup(g0.localNode(), String.valueOf(i))) {
        key = String.valueOf(i);

        break;
      }
    }

    assertNotNull(key);

    cache.put(key, key); // Create entry in near cache, it is invalidated if INVALIDATE flag is set.

    assertNotNull(cache.peek(key));

    GridClientData d = client.data(PARTITIONED_CACHE_NAME);

    d.flagsOn(GridClientCacheFlag.INVALIDATE).put(key, "zzz");

    for (Grid g : G.allGrids()) {
      cache = g.cache(PARTITIONED_CACHE_NAME);

      if (cache.affinity().isPrimaryOrBackup(g.localNode(), key))
        assertEquals("zzz", cache.peek(key));
      else assertNull(cache.peek(key));
    }
  }
示例#3
0
  /**
   * Listen to events coming from all grid nodes.
   *
   * @throws GridException If failed.
   */
  private static void remoteListen() throws GridException {
    Grid g = GridGain.grid();

    GridCache<Integer, String> cache = g.cache(CACHE_NAME);

    // Register remote event listeners on all nodes running cache.
    GridFuture<?> fut =
        g.forCache(CACHE_NAME)
            .events()
            .remoteListen(
                // This optional local callback is called for each event notification
                // that passed remote predicate filter.
                new GridBiPredicate<UUID, GridCacheEvent>() {
                  @Override
                  public boolean apply(UUID nodeId, GridCacheEvent evt) {
                    System.out.println();
                    System.out.println(
                        "Received event [evt="
                            + evt.name()
                            + ", key="
                            + evt.key()
                            + ", oldVal="
                            + evt.oldValue()
                            + ", newVal="
                            + evt.newValue());

                    return true; // Return true to continue listening.
                  }
                },
                // Remote filter which only accepts events for keys that are
                // greater or equal than 10 and if local node is primary for this key.
                new GridPredicate<GridCacheEvent>() {
                  /** Auto-inject grid instance. */
                  @GridInstanceResource private Grid g;

                  @Override
                  public boolean apply(GridCacheEvent evt) {
                    Integer key = evt.key();

                    return key >= 10
                        && g.cache(CACHE_NAME).affinity().isPrimary(g.localNode(), key);
                  }
                },
                // Types of events for which listeners are registered.
                EVT_CACHE_OBJECT_PUT,
                EVT_CACHE_OBJECT_READ,
                EVT_CACHE_OBJECT_REMOVED);

    // Wait until event listeners are subscribed on all nodes.
    fut.get();

    int keyCnt = 20;

    // Generate cache events.
    for (int i = 0; i < keyCnt; i++) cache.putx(i, Integer.toString(i));
  }
示例#4
0
  /**
   * Runs JDBC example.
   *
   * @param args Command line arguments.
   * @throws Exception In case of error.
   */
  public static void main(String[] args) throws Exception {
    Grid grid = G.start("examples/config/spring-cache.xml");

    Connection conn = null;

    try {
      // Populate cache with data.
      populate(grid.cache(CACHE_NAME));

      // Register JDBC driver.
      Class.forName("org.gridgain.jdbc.GridJdbcDriver");

      // Open JDBC connection.
      conn =
          DriverManager.getConnection("jdbc:gridgain://localhost/" + CACHE_NAME, configuration());

      X.println(">>>");

      // Query all persons.
      queryAllPersons(conn);

      X.println(">>>");

      // Query person older than 30 years.
      queryPersons(conn, 30);

      X.println(">>>");

      // Query persons working in GridGain.
      queryPersonsInOrganization(conn, "GridGain");

      X.println(">>>");
    } finally {
      // Close JDBC connection.
      if (conn != null) conn.close();

      G.stop(true);
    }
  }
  /**
   * Runs basic cache example.
   *
   * @param args Command line arguments, none required.
   * @throws Exception If example execution failed.
   */
  public static void main(String[] args) throws Exception {
    final Grid g =
        args.length == 0 ? G.start("examples/config/spring-cache.xml") : G.start(args[0]);

    try {
      // Subscribe to events on every node, so we can visualize what's
      // happening in remote caches.
      g.run(
          BROADCAST,
          new CA() {
            @Override
            public void apply() {
              GridLocalEventListener lsnr =
                  new GridLocalEventListener() {
                    @Override
                    public void onEvent(GridEvent event) {
                      switch (event.type()) {
                        case EVT_CACHE_OBJECT_PUT:
                        case EVT_CACHE_OBJECT_READ:
                        case EVT_CACHE_OBJECT_REMOVED:
                          {
                            GridCacheEvent e = (GridCacheEvent) event;

                            X.println("Cache event [name=" + e.name() + ", key=" + e.key() + ']');
                          }
                      }
                    }
                  };

              GridNodeLocal<String, GridLocalEventListener> loc = g.nodeLocal();

              GridLocalEventListener prev = loc.remove("lsnr");

              // If there is a listener subscribed from previous runs, unsubscribe it.
              if (prev != null) g.removeLocalEventListener(prev);

              // Record new listener, so we can check it on next run.
              loc.put("lsnr", lsnr);

              // Subscribe listener.
              g.addLocalEventListener(lsnr, EVTS_CACHE);
            }
          });

      final GridCacheProjection<Integer, String> cache =
          g.cache(CACHE_NAME).projection(Integer.class, String.class);

      final int keyCnt = 20;

      // Store keys in cache.
      for (int i = 0; i < keyCnt; i++) cache.putx(i, Integer.toString(i));

      // Peek and get on local node.
      for (int i = 0; i < keyCnt; i++) {
        X.println("Peeked [key=" + i + ", val=" + cache.peek(i) + ']');
        X.println("Got [key=" + i + ", val=" + cache.get(i) + ']');
      }

      // Projection (view) for remote nodes.
      GridProjection rmts = g.remoteProjection();

      if (!rmts.isEmpty()) {
        // Peek and get on remote nodes (comment it out if output gets too crowded).
        g.remoteProjection()
            .run(
                BROADCAST,
                new GridAbsClosureX() {
                  @Override
                  public void applyx() throws GridException {
                    for (int i = 0; i < keyCnt; i++) {
                      X.println("Peeked [key=" + i + ", val=" + cache.peek(i) + ']');
                      X.println("Got [key=" + i + ", val=" + cache.get(i) + ']');
                    }
                  }
                });
      }
    } finally {
      G.stop(true);
    }
  }