예제 #1
0
  /**
   * {@inheritDoc} Sets up two caches: cache1 is local. cache2 is to be receive updates
   *
   * @throws Exception
   */
  @Override
  @Before
  public void setUp() throws Exception {

    // Required to get SoftReference tests to pass. The VM clean up SoftReferences rather than
    // allocating
    // memory to -Xmx!
    //        forceVMGrowth();
    //        System.gc();
    MulticastKeepaliveHeartbeatSender.setHeartBeatInterval(1000);

    manager1 = new CacheManager(AbstractCachePerfTest.TEST_CONFIG_DIR + "ehcache-distributed1.xml");
    manager2 = new CacheManager(AbstractCachePerfTest.TEST_CONFIG_DIR + "ehcache-distributed2.xml");
    manager3 = new CacheManager(AbstractCachePerfTest.TEST_CONFIG_DIR + "ehcache-distributed3.xml");
    manager4 = new CacheManager(AbstractCachePerfTest.TEST_CONFIG_DIR + "ehcache-distributed4.xml");
    manager5 = new CacheManager(AbstractCachePerfTest.TEST_CONFIG_DIR + "ehcache-distributed5.xml");

    // manager6 = new CacheManager(AbstractCacheTest.TEST_CONFIG_DIR +
    // "distribution/ehcache-distributed-jndi6.xml");

    // allow cluster to be established
    Thread.sleep(1020);

    cache1 = manager1.getCache(cacheName);
    cache1.removeAll();

    cache2 = manager2.getCache(cacheName);
    cache2.removeAll();

    // enable distributed removeAlls to finish
    Thread.sleep(1500);
  }
  /** ** Private Methods ** */
  private CacheEntry getCache(ProceedingJoinPoint pjp) {

    String name = getCacheName(pjp);

    CacheEntry entry = _entries.get(name);

    if (entry == null) {
      Method method = _cacheableMethodKeyFactoryManager.getMatchingMethodForJoinPoint(pjp);
      CacheableMethodKeyFactory keyFactory = getKeyFactory(pjp, method);
      boolean valueSerializable = isValueSerializable(pjp, method);
      Cache cache = _cacheManager.getCache(name);
      if (cache == null) {
        cache = createCache(pjp, name);
        if (cache == null) {
          _cacheManager.addCache(name);
          cache = _cacheManager.getCache(name);
        } else {
          _cacheManager.addCache(cache);
        }
      }
      entry = new CacheEntry(keyFactory, valueSerializable, cache);
      _entries.put(name, entry);
    }
    return entry;
  }
예제 #3
0
  /**
   * Test.
   *
   * @throws IOException e
   */
  @Test
  public void testCache() throws IOException {
    final String cacheName = "test 1";
    final CacheManager cacheManager = CacheManager.getInstance();
    cacheManager.addCache(cacheName);
    final String cacheName2 = "test 2";
    try {
      final Cache cache = cacheManager.getCache(cacheName);
      cache.put(new Element(1, Math.random()));
      cache.get(1);
      cache.get(0);
      cacheManager.addCache(cacheName2);
      final Cache cache2 = cacheManager.getCache(cacheName2);
      cache2.getCacheConfiguration().setOverflowToDisk(false);
      cache2.getCacheConfiguration().setEternal(true);
      cache2.getCacheConfiguration().setMaxElementsInMemory(0);

      // JavaInformations doit être réinstancié pour récupérer les caches
      final List<JavaInformations> javaInformationsList2 =
          Collections.singletonList(new JavaInformations(null, true));
      final HtmlReport htmlReport =
          new HtmlReport(collector, null, javaInformationsList2, Period.TOUT, writer);
      htmlReport.toHtml(null, null);
      assertNotEmptyAndClear(writer);
      setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, "false");
      htmlReport.toHtml(null, null);
      assertNotEmptyAndClear(writer);
    } finally {
      setProperty(Parameter.SYSTEM_ACTIONS_ENABLED, null);
      cacheManager.removeCache(cacheName);
      cacheManager.removeCache(cacheName2);
    }
  }
예제 #4
0
  /** Drive everything to point of breakage within a 64MB VM. */
  public void xTestHugePutsBreaksAsynchronous() throws CacheException, InterruptedException {

    // Give everything a chance to startup
    StopWatch stopWatch = new StopWatch();
    Integer index = null;
    for (int i = 0; i < 500; i++) {
      for (int j = 0; j < 1000; j++) {
        index = Integer.valueOf(((1000 * i) + j));
        cache1.put(
            new Element(
                index,
                "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
                    + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
                    + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
                    + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
                    + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
      }
    }
    long elapsed = stopWatch.getElapsedTime();
    long putTime = ((elapsed / 1000));
    LOG.info("Put Elapsed time: " + putTime);
    // assertTrue(putTime < 8);

    assertEquals(100000, cache1.getSize());

    Thread.sleep(100000);
    assertEquals(20000, manager2.getCache("sampleCache1").getSize());
    assertEquals(20000, manager3.getCache("sampleCache1").getSize());
    assertEquals(20000, manager4.getCache("sampleCache1").getSize());
    assertEquals(20000, manager5.getCache("sampleCache1").getSize());
  }
예제 #5
0
 private void updateSchoolCache(SchoolAccount accnt) {
   cacheManager
       .getCache(CacheVariables.CACHE_SCHOOL_ACCOUNTS_BY_USERNAME)
       .put(new Element(accnt.getUsername(), accnt));
   cacheManager
       .getCache(CacheVariables.CACHE_ACCOUNTS_BY_UUID)
       .put(new Element(accnt.getUuid(), accnt));
 }
 private void clearChache() throws IOException {
   CacheManager cacheManager =
       CacheManager.create(new ClassPathResource("echache.xml").getInputStream());
   Cache cache1 = cacheManager.getCache("turmas-efetivas-cache");
   Cache cache2 = cacheManager.getCache("turmas-pendencias-cache");
   cache1.removeAll();
   cache2.removeAll();
 }
예제 #7
0
 public Cache getEhCache() {
   Cache cache = ehcacheManager.getCache(name);
   if (null == cache) {
     ehcacheManager.addCache(name);
     return ehcacheManager.getCache(name);
   } else {
     return cache;
   }
 }
예제 #8
0
 /**
  * 获得一个Cache,没有则创建一个。
  *
  * @param cacheName
  * @return
  */
 private static Cache getCache(String cacheName) {
   Cache cache = cacheManager.getCache(cacheName);
   if (cache == null) {
     cacheManager.addCache(cacheName);
     cache = cacheManager.getCache(cacheName);
     cache.getCacheConfiguration().setEternal(true);
   }
   return cache;
 }
예제 #9
0
파일: EhCache.java 프로젝트: javajiao/mg4
 /**
  * Builds a Cache.
  *
  * <p>Even though this method provides properties, they are not used. Properties for EHCache are
  * specified in the ehcache.xml file. Configuration will be read from ehcache.xml for a cache
  * declaration where the name attribute matches the name parameter in this builder.
  *
  * @param name the name of the cache. Must match a cache configured in ehcache.xml
  * @param properties not used
  * @return a newly built cache will be built and initialised
  * @throws CacheException inter alia, if a cache of the same name already exists
  */
 public void init() throws CacheException {
   try {
     manager = new CacheManager();
     ehcache = manager.getCache(G4_RESOURCE_GROUP);
     if (ehcache == null) {
       logger.warn("Could not find configuration [" + G4_RESOURCE_GROUP + "]; using defaults.");
       manager.addCache(G4_RESOURCE_GROUP);
       ehcache = manager.getCache(G4_RESOURCE_GROUP);
       logger.debug("started EHCache region: " + G4_RESOURCE_GROUP);
     }
   } catch (net.sf.ehcache.CacheException e) {
     throw new CacheException(e);
   }
 }
예제 #10
0
 @Override
 public <T extends GeneralMessage> boolean isNewMessage(String userId, T message, Class<T> T) {
   Cache cache = cm.getCache("Messages");
   String key = message.getUniqueFieldValue() + userId;
   Element element = cache.get(key);
   if (element != null) {
     return (Boolean) element.getValue();
   }
   Query<UnreaddenMessage> isUnread =
       ds.createQuery(UnreaddenMessage.class)
           .field("userId")
           .equal(userId)
           .field("message")
           .equal(new Key<T>(T, message.getId()));
   Query<ReaddenMessage> isRead =
       ds.createQuery(ReaddenMessage.class)
           .field("userId")
           .equal(userId)
           .field("messageUniqueId")
           .equal(message.getUniqueFieldValue().toString());
   Boolean newMessage = isUnread.countAll() <= 0 && isRead.countAll() <= 0;
   element = new Element(key, new Boolean(false));
   cache.put(element);
   return newMessage;
 }
예제 #11
0
 /** Load up the test cache */
 protected void setUp() throws Exception {
   super.setUp();
   manager = new CacheManager();
   cache = manager.getCache("sampleIdlingExpiringCache");
   selfPopulatingCache = new SelfPopulatingCache(cache, new CountingCacheEntryFactory("value"));
   cacheEntryFactoryRequests = 0;
 }
예제 #12
0
  /**
   * Loads an existing EhCache from the cache manager, or starts a new cache if one is not found.
   *
   * @param name the name of the cache to load/create.
   */
  public final <K, V> Cache<K, V> getCache(String name) throws CacheException {

    if (log.isTraceEnabled()) {
      log.trace("Acquiring EhCache instance named [" + name + "]");
    }

    try {
      net.sf.ehcache.Ehcache cache = ensureCacheManager().getEhcache(name);
      if (cache == null) {
        if (log.isInfoEnabled()) {
          log.info("Cache with name '{}' does not yet exist.  Creating now.", name);
        }
        this.manager.addCache(name);

        cache = manager.getCache(name);

        if (log.isInfoEnabled()) {
          log.info("Added EhCache named [" + name + "]");
        }
      } else {
        if (log.isInfoEnabled()) {
          log.info("Using existing EHCache named [" + cache.getName() + "]");
        }
      }
      return new EhCache<K, V>(cache);
    } catch (net.sf.ehcache.CacheException e) {
      throw new CacheException(e);
    }
  }
예제 #13
0
 @Override
 public EhCache buildCache(CacheSetting setting) throws CacheException {
   String name = StringUtil.joinString(setting.getRegion(), setting.getConfigKey());
   EhCache ehcache = cacheManager.get(name);
   if (ehcache == null) {
     try {
       synchronized (cacheManager) {
         ehcache = cacheManager.get(name);
         if (ehcache == null) {
           // log.debug("Could not find configuration [" + name
           // + "]; using defaults.");
           Ehcache ehcache2 = manager.addCacheIfAbsent(name);
           if (ehcache2 != null) {
             if (setting.getCacheExpire() == CacheExpire.SlidingTime) {
               ehcache2.getCacheConfiguration().setTimeToIdleSeconds(setting.getExpireTime());
               ehcache2.getCacheConfiguration().setTimeToLiveSeconds(0);
             } else if (setting.getCacheExpire() == CacheExpire.AbsoluteTime) {
               ehcache2.getCacheConfiguration().setTimeToLiveSeconds(setting.getExpireTime());
               ehcache2.getCacheConfiguration().setTimeToIdleSeconds(0);
             }
           }
           Cache cache = manager.getCache(name);
           // log.debug("started EHCache region: " + name);
           LoggerFactory.getLogger(this.getClass()).info("init ehcache " + cache);
           ehcache = new EhCache(cache, setting);
           cacheManager.put(name, ehcache);
         }
       }
     } catch (Exception e) {
       throw new CacheException(e);
     }
   }
   return ehcache;
 }
예제 #14
0
 /** {@inheritDoc} */
 @Override
 public void clear(final String context) {
   final Ehcache ehCache = manager.getCache(context);
   if (ehCache != null) {
     ehCache.removeAll();
   }
 }
 /** @see com.dianping.cache.core.CacheClient#clear() */
 @Override
 public void clear() {
   defaultBlockingCache.removeAll();
   for (String cacheName : manager.getCacheNames()) {
     manager.getCache(cacheName).removeAll();
   }
 }
예제 #16
0
  @RequestMapping("{cacheName}/{key}/details")
  @ResponseBody
  public Object keyDetail(
      @PathVariable("cacheName") String cacheName, @PathVariable("key") String key, Model model) {

    Element element = cacheManager.getCache(cacheName).get(key);

    String dataPattern = "yyyy-MM-dd hh:mm:ss";
    Map<String, Object> data = Maps.newHashMap();
    data.put("objectValue", element.getObjectValue().toString());
    data.put("size", PrettyMemoryUtils.prettyByteSize(element.getSerializedSize()));
    data.put("hitCount", element.getHitCount());

    Date latestOfCreationAndUpdateTime = new Date(element.getLatestOfCreationAndUpdateTime());
    data.put(
        "latestOfCreationAndUpdateTime",
        DateFormatUtils.format(latestOfCreationAndUpdateTime, dataPattern));
    Date lastAccessTime = new Date(element.getLastAccessTime());
    data.put("lastAccessTime", DateFormatUtils.format(lastAccessTime, dataPattern));
    if (element.getExpirationTime() == Long.MAX_VALUE) {
      data.put("expirationTime", "不过期");
    } else {
      Date expirationTime = new Date(element.getExpirationTime());
      data.put("expirationTime", DateFormatUtils.format(expirationTime, dataPattern));
    }

    data.put("timeToIdle", element.getTimeToIdle());
    data.put("timeToLive", element.getTimeToLive());
    data.put("version", element.getVersion());

    return data;
  }
예제 #17
0
 public <T extends ISocioObject> void saveObject(T object) throws DuplicateMySocioObjectException {
   if (object instanceof IUniqueObject) {
     IUniqueObject uniqueObject = (IUniqueObject) object;
     Cache cache = cm.getCache("Objects");
     String key = uniqueObject.getUniqueFieldName() + uniqueObject.getUniqueFieldValue();
     Element element = cache.get(key);
     if (element != null) {
       ((SocioObject) object).setId((ObjectId) element.getValue());
       return;
     }
     @SuppressWarnings("unchecked")
     Query<T> q =
         (Query<T>)
             ds.createQuery(object.getClass())
                 .field(uniqueObject.getUniqueFieldName())
                 .equal(uniqueObject.getUniqueFieldValue());
     T objectT = (T) q.get();
     if (objectT != null) {
       ((SocioObject) object).setId(objectT.getId());
       element = new Element(key, objectT.getId());
       cache.put(element);
       logger.info(
           "Duplicate object of type: " + object.getClass() + " for query: " + q.toString());
       throw new DuplicateMySocioObjectException(
           "Duplicate object of type: " + object.getClass() + " for query: " + q.toString());
     }
   }
   ds.save(object);
 }
예제 #18
0
  @PostConstruct
  public void initialize() {
    stats = new Stats();

    boolean cacheExists = cacheManager.cacheExists(getName());

    if (cacheExists) {
      if (failOnDuplicateCache) {
        throw new RuntimeException("A previous cache with name [" + getName() + "] exists.");
      } else {
        log.warn("skip duplicate cache " + getName());
        ehcache = cacheManager.getCache(getName());
      }
    }

    if (!cacheExists) {
      ehcache =
          new Cache(
              getName(),
              getMaxElementsInMemory(),
              getMemoryStoreEvictionPolicy(),
              isOverflowToDisk(),
              getDiskStorePath(),
              isEternal(),
              getTimeToLiveSeconds(),
              getTimeToIdleSeconds(),
              isDiskPersistent(),
              getDiskExpiryThreadIntervalSeconds(),
              null);

      cacheManager.addCache(ehcache);
      ehcache.setStatisticsEnabled(statisticsEnabled);
    }
  }
  @Test
  public void testParallelShutdown() throws Exception {
    final CacheManager manager =
        new CacheManager(
            new Configuration()
                .name("testEqualsDriver")
                .cache(
                    new CacheConfiguration()
                        .name("parallel")
                        .maxBytesLocalHeap(64, MemoryUnit.MEGABYTES)));
    Cache parallel = manager.getCache("parallel");
    CacheDriver loadParallel =
        CacheLoader.load(ehcache(parallel))
            .using(StringGenerator.integers(), ByteArrayGenerator.fixedSize(128))
            .sequentially()
            .untilFilled();
    final CacheDriver driver = ParallelDriver.inParallel(4, loadParallel);

    await()
        .atMost(20, TimeUnit.SECONDS)
        .until(
            new Callable<Boolean>() {
              @Override
              public Boolean call() throws Exception {
                driver.run();
                return true;
              }
            });
    manager.shutdown();
  }
예제 #20
0
  @Bean
  public CacheManager cacheManager() {
    log.debug("Starting Ehcache");
    cacheManager = net.sf.ehcache.CacheManager.create();
    cacheManager
        .getConfiguration()
        .setMaxBytesLocalHeap(
            env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M"));
    log.debug("Registering Ehcache Metrics gauges");
    Set<EntityType<?>> entities = entityManager.getMetamodel().getEntities();
    for (EntityType<?> entity : entities) {

      String name = entity.getName();
      if (name == null || entity.getJavaType() != null) {
        name = entity.getJavaType().getName();
      }
      Assert.notNull(name, "entity cannot exist without a identifier");

      net.sf.ehcache.Cache cache = cacheManager.getCache(name);
      if (cache != null) {
        cache
            .getCacheConfiguration()
            .setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L));
        net.sf.ehcache.Ehcache decoratedCache =
            InstrumentedEhcache.instrument(metricRegistry, cache);
        cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache);
      }
    }
    EhCacheCacheManager ehCacheManager = new EhCacheCacheManager();
    ehCacheManager.setCacheManager(cacheManager);
    return ehCacheManager;
  }
예제 #21
0
  @Test
  public void testConfigFileHonorsClusteringOff() {
    final CacheManager cacheManager =
        new CacheManager(
            CacheManager.class.getResourceAsStream("/terracotta/ehcache-event-replication.xml"));
    try {
      final Cache cache = cacheManager.getCache("replication");
      assertThat(cache, notNullValue());
      final TerracottaConfiguration terracottaConfiguration =
          cache.getCacheConfiguration().getTerracottaConfiguration();
      assertThat(terracottaConfiguration, notNullValue());
      assertThat(terracottaConfiguration.isClustered(), is(false));
      final List eventListenerConfigurations =
          cache.getCacheConfiguration().getCacheEventListenerConfigurations();
      assertThat(eventListenerConfigurations, notNullValue());
      assertThat(eventListenerConfigurations.size(), is(1));
      assertThat(
          ((CacheConfiguration.CacheEventListenerFactoryConfiguration)
                  eventListenerConfigurations.get(0))
              .getFullyQualifiedClassPath(),
          equalTo(TerracottaCacheEventReplicationFactory.class.getName()));
      cache.put(new Element("key", "value"));
      assertThat((String) cache.get("key").getValue(), equalTo("value"));

    } finally {
      cacheManager.shutdown();
    }
  }
예제 #22
0
  @Override
  public List<BounceProxyRecord> getAssignableBounceProxies() {

    if (log.isTraceEnabled()) {
      log.trace("Retrieving assignable bounce proxies from cache {}", cacheName);
      tracePeers();
    }

    List<BounceProxyRecord> result = new LinkedList<BounceProxyRecord>();

    Cache cache = manager.getCache(cacheName);

    @SuppressWarnings("unchecked")
    List keys = cache.getKeys();
    Map<Object, Element> elements = cache.getAll(keys);

    for (Element element : elements.values()) {
      BounceProxyRecord bounceProxyRecord = getBounceProxyRecordFromElement(element);
      if (bounceProxyRecord.getStatus().isAssignable()) {
        result.add(bounceProxyRecord);
      }
    }

    return result;
  }
  @Around("findAllComPendendias()")
  public Object findAllTurmasComPendenciasMethodInterceptor(ProceedingJoinPoint joinPoint)
      throws Throwable {
    Object result = null;
    CacheManager cacheManager =
        CacheManager.create(new ClassPathResource("echache.xml").getInputStream());
    Cache cache = cacheManager.getCache("turmas-pendencias-cache");

    Object[] args = joinPoint.getArgs();

    if (args[0] == null || args[1] == null) {
      result = joinPoint.proceed();
      return result;
    }
    SimpleDateFormat df = new SimpleDateFormat("yyyy");
    String exercicio = df.format((Date) args[0]);
    String organizacao = ((Long) args[1]).toString();

    String key = exercicio + "-" + organizacao;
    Element element = cache.get(key);

    if (element == null) {
      result = joinPoint.proceed();
      cache.put(new Element(key, result));
    } else {
      Logger.getLogger(this.getClass().getName())
          .log(Level.INFO, "Dados presentes no cache, não foi necessário acesso ao banco de dados");
      result = element.getValue();
    }
    return result;
  }
  @Around("findTurmaEfetiva()")
  public Object findTurmaEfetivaMethodInterceptor(ProceedingJoinPoint joinPoint) throws Throwable {
    Object result = null;
    CacheManager cacheManager =
        CacheManager.create(new ClassPathResource("echache.xml").getInputStream());
    Cache cache = cacheManager.getCache("turmas-efetivas-cache");

    Object[] args = joinPoint.getArgs();

    Long turmaId = (Long) args[0];

    Element element = cache.get(turmaId);

    if (element == null) {
      result = joinPoint.proceed();
      cache.put(new Element(turmaId, result));

    } else {
      Logger.getLogger(this.getClass().getName())
          .log(
              Level.INFO,
              "Dados presentes no cache de turmas, não foi necessário acesso ao banco de dados");
      result = element.getValue();
    }
    return result;
  }
  protected static CacheManager getCacheManagerMaxEntries() {
    Configuration configuration = new Configuration();
    configuration.setName("testCacheManager");
    configuration.addTerracottaConfig(new TerracottaClientConfiguration().url(CLUSTER_URL));
    CacheConfiguration defaultCacheConfiguration =
        new CacheConfiguration()
            .eternal(true)
            .terracotta(new TerracottaConfiguration())
            .maxEntriesLocalHeap(10000);
    CacheConfiguration cacheConfiguration =
        new CacheConfiguration()
            .name("testCache")
            .terracotta(new TerracottaConfiguration())
            .maxEntriesLocalHeap(10000);
    configuration.setDefaultCacheConfiguration(defaultCacheConfiguration);
    configuration.addCache(cacheConfiguration);
    ManagementRESTServiceConfiguration managementRESTServiceConfiguration =
        new ManagementRESTServiceConfiguration();
    managementRESTServiceConfiguration.setBind("0.0.0.0:" + STANDALONE_REST_AGENT_PORT);
    managementRESTServiceConfiguration.setEnabled(true);
    configuration.addManagementRESTService(managementRESTServiceConfiguration);

    CacheManager mgr = new CacheManager(configuration);
    Cache exampleCache = mgr.getCache("testCache");
    assert (exampleCache != null);
    return mgr;
  }
  protected static CacheManager getCacheManagerMaxbytes() {
    Configuration configuration = new Configuration();
    configuration.setName("testCacheManagerProgrammatic");
    configuration.setMaxBytesLocalDisk("10M");
    configuration.setMaxBytesLocalHeap("5M");
    TerracottaClientConfiguration terracottaConfiguration =
        new TerracottaClientConfiguration().url(CLUSTER_URL);
    configuration.addTerracottaConfig(terracottaConfiguration);
    CacheConfiguration myCache =
        new CacheConfiguration()
            .eternal(false)
            .name("testCache2")
            .terracotta(new TerracottaConfiguration());
    configuration.addCache(myCache);
    ManagementRESTServiceConfiguration managementRESTServiceConfiguration =
        new ManagementRESTServiceConfiguration();
    managementRESTServiceConfiguration.setBind("0.0.0.0:" + STANDALONE_REST_AGENT_PORT);
    managementRESTServiceConfiguration.setEnabled(true);
    configuration.addManagementRESTService(managementRESTServiceConfiguration);

    CacheManager mgr = new CacheManager(configuration);
    Cache exampleCache = mgr.getCache("testCache2");
    assert (exampleCache != null);
    return mgr;
  }
 public EntityPersonAttributesGroupStore() {
   super();
   ApplicationContext applicationContext = ApplicationContextLocator.getApplicationContext();
   this.personAttributesGroupDefinitionDao =
       applicationContext.getBean(
           "personAttributesGroupDefinitionDao", IPersonAttributesGroupDefinitionDao.class);
   CacheManager cacheManager = applicationContext.getBean("cacheManager", CacheManager.class);
   this.entityGroupCache =
       cacheManager.getCache(
           "org.jasig.portal.groups.pags.dao.EntityPersonAttributesGroupStore.entityGroup");
   this.pagsGroupCache =
       cacheManager.getCache(
           "org.jasig.portal.groups.pags.dao.EntityPersonAttributesGroupStore.pagsGroup");
   this.membershipCache =
       cacheManager.getCache(
           "org.jasig.portal.groups.pags.dao.EntityPersonAttributesGroupStore.membership");
 }
예제 #28
0
 private Ehcache getEHCache(final String context) {
   final Ehcache ehCache = manager.getCache(context);
   Assertion.checkNotNull(
       ehCache,
       "Cache {0} are not yet registered. Add it into a file ehcache.xml and put it into the WEB-INF directory of your webapp.",
       context);
   return ehCache;
 }
 public void afterPropertiesSet() throws Exception {
   guestAnnouncementCache = cm.getCache("guestAnnouncementCache");
   if (guestAnnouncementCache == null) {
     throw new BeanCreationException("Required guestAnnouncementCache could not be loaded.");
   } else {
     logger.debug("guestAnnouncementCache created.");
   }
 }
예제 #30
-1
  /**
   * Performance and capacity tests.
   *
   * <p>
   */
  @Test
  public void testBootstrap() throws CacheException, InterruptedException, RemoteException {

    // load up some data
    StopWatch stopWatch = new StopWatch();
    Integer index = null;
    for (int i = 0; i < 2; i++) {
      for (int j = 0; j < 1000; j++) {
        index = Integer.valueOf(((1000 * i) + j));
        cache1.put(
            new Element(
                index,
                "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
                    + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
                    + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
                    + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
                    + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
      }
    }
    long elapsed = stopWatch.getElapsedTime();
    long putTime = ((elapsed / 1000));
    LOG.info("Put Elapsed time: " + putTime);

    assertEquals(2000, cache1.getSize());

    Thread.sleep(7000);
    assertEquals(2000, manager2.getCache("sampleCache1").getSize());
    assertEquals(2000, manager3.getCache("sampleCache1").getSize());
    assertEquals(2000, manager4.getCache("sampleCache1").getSize());
    assertEquals(2000, manager5.getCache("sampleCache1").getSize());

    // now test bootstrap
    manager1.addCache("bootStrapResults");
    Cache cache = manager1.getCache("bootStrapResults");
    List cachePeers = manager1.getCacheManagerPeerProvider("RMI").listRemoteCachePeers(cache1);
    CachePeer cachePeer = (CachePeer) cachePeers.get(0);

    List keys = cachePeer.getKeys();
    assertEquals(2000, keys.size());

    Element firstElement = cachePeer.getQuiet((Serializable) keys.get(0));
    long size = firstElement.getSerializedSize();
    assertEquals(504, size);

    int chunkSize = (int) (5000000 / size);

    List requestChunk = new ArrayList();
    for (int i = 0; i < keys.size(); i++) {
      Serializable serializable = (Serializable) keys.get(i);
      requestChunk.add(serializable);
      if (requestChunk.size() == chunkSize) {
        fetchAndPutElements(cache, requestChunk, cachePeer);
        requestChunk.clear();
      }
    }
    // get leftovers
    fetchAndPutElements(cache, requestChunk, cachePeer);

    assertEquals(keys.size(), cache.getSize());
  }