Java Code Examples for net.sf.ehcache.Cache#put()

The following examples show how to use net.sf.ehcache.Cache#put() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RegressServiceImpl.java    From jvm-sandbox-repeater with Apache License 2.0 6 votes vote down vote up
@Override
public RepeaterResult<Regress> getRegressWithCache(String name) {
    Cache cache = cacheManager.getCache("regressCache");
    // priority use of the cache data
    Element element = cache.get(name);
    Regress regress;
    if (element == null) {
        regress = getRegressInternal(name, 1);
        cache.put(new Element(name, regress));
    } else {
        regress = (Regress) element.getObjectValue();
    }
    return RepeaterResult.builder()
            .data(regress)
            .success(true)
            .message("operate success")
            .build();
}
 
Example 2
Source File: CacheListenerAspect.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@Around("execution(* org.packt.aop.transaction.dao.impl.EmployeeDaoImpl.getEmployees(..))")
public Object cacheMonitor(ProceedingJoinPoint joinPoint) throws Throwable  {
   logger.info("executing " + joinPoint.getSignature().getName());
   Cache cache = cacheManager.getCache("employeesCache");
  
   logger.info("cache detected is  " + cache.getName());
   logger.info("begin caching.....");
   String key = joinPoint.getSignature().getName();
   logger.info(key);
   if(cache.get(key) == null){
	   logger.info("caching new Object.....");
	   Object result = joinPoint.proceed();
	   cache.put(new Element(key, result)); 	   
	   return result;
   }else{
	   logger.info("getting cached Object.....");
	   return cache.get(key).getObjectValue();
   }
}
 
Example 3
Source File: BounceProxyEhcacheAdapter.java    From joynr with Apache License 2.0 6 votes vote down vote up
@Override
public void updateChannelAssignment(String ccid, BounceProxyInformation bpInfo) throws IllegalArgumentException {

    if (log.isTraceEnabled()) {
        log.trace("Update channel assignment for bounce proxy {} in cache {}", bpInfo.getId(), cacheName);
        tracePeers();
    }

    Cache cache = manager.getCache(cacheName);
    Element element = cache.get(bpInfo.getId());

    if (element == null) {
        throw new IllegalArgumentException("No bounce proxy with ID '" + bpInfo.getId() + "' exists");
    }

    BounceProxyRecord bpRecord = getBounceProxyRecordFromElement(element);
    bpRecord.addAssignedChannel(ccid);
    Element updatedElement = new Element(bpInfo.getId(), bpRecord);
    cache.put(updatedElement);
}
 
Example 4
Source File: EhCacheDataCache.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public TableModel put( final DataCacheKey key, final TableModel model ) {
  if ( model.getRowCount() > maximumRows ) {
    return model;
  }

  // Only copy if safe to do so. Check for whitelist of good column types ..
  if ( CachableTableModel.isSafeToCache( model ) == false ) {
    return model;
  }

  final Cache cache;
  synchronized ( this ) {
    initialize();
    cache = this.cache;
  }

  final TableModel cacheModel = new CachableTableModel( model );
  cache.put( new Element( key, cacheModel ) );
  return cacheModel;
}
 
Example 5
Source File: DomainAccessControlStoreEhCache.java    From joynr with Apache License 2.0 5 votes vote down vote up
private <T extends ControlEntry> Boolean updateAce(T accessControlEntry, CacheId cacheId, Object aceKey) {
    Cache cache = getCache(cacheId);
    boolean updateSuccess = false;
    try {
        cache.put(new Element(aceKey, accessControlEntry));
        updateSuccess = true;
    } catch (IllegalArgumentException | IllegalStateException | CacheException e) {
        logger.error("Update {} failed:", cacheId, e);
    }

    return updateSuccess;
}
 
Example 6
Source File: ECacheProvider.java    From anyline with Apache License 2.0 5 votes vote down vote up
public void put(String channel, Element element){
	Cache cache = getCache(channel);
	if(null != cache){
		cache.put(element);
    	if(ConfigTable.isDebug() && log.isWarnEnabled()){
    		log.warn("[存储缓存数据][channel:{}][key:{}][生存:0/{}]",channel,element.getObjectKey(),cache.getCacheConfiguration().getTimeToLiveSeconds());
    	}
	}
}
 
Example 7
Source File: DomainAccessControlStoreEhCache.java    From joynr with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean updateDomainRole(DomainRoleEntry updatedEntry) {
    boolean updateSuccess = false;
    Cache cache = getCache(CacheId.DOMAIN_ROLES);
    UserRoleKey dreKey = new UserRoleKey(updatedEntry.getUid(), updatedEntry.getRole());
    try {
        cache.put(new Element(dreKey, updatedEntry));
        updateSuccess = true;
    } catch (IllegalArgumentException | IllegalStateException | CacheException e) {
        logger.error("UpdateDomainRole failed.", e);
    }

    return updateSuccess;
}
 
Example 8
Source File: BounceProxyEhcacheAdapter.java    From joynr with Apache License 2.0 5 votes vote down vote up
@Override
public void updateBounceProxy(BounceProxyRecord bpRecord) throws IllegalArgumentException {

    if (log.isTraceEnabled()) {
        log.trace("updateBounceProxy {} in cache {}", bpRecord.getBounceProxyId(), cacheName);
        tracePeers();
    }

    Cache cache = manager.getCache(cacheName);
    Element element = new Element(bpRecord.getBounceProxyId(), bpRecord);
    cache.put(element);
}
 
Example 9
Source File: BounceProxyEhcacheAdapter.java    From joynr with Apache License 2.0 5 votes vote down vote up
@Override
public void addBounceProxy(ControlledBounceProxyInformation bpInfo) throws IllegalArgumentException {

    if (log.isTraceEnabled()) {
        log.trace("addBounceProxy {} to cache {}", bpInfo.getId(), cacheName);
        tracePeers();
    }

    Cache cache = manager.getCache(cacheName);
    Element element = new Element(bpInfo.getId(), new BounceProxyRecord(bpInfo));
    cache.put(element);
}
 
Example 10
Source File: EhcacheService.java    From jeecg with Apache License 2.0 5 votes vote down vote up
@Override
public void put(String cacheName, Object key, Object value) {
	log.debug("  EhcacheService  put cacheName: [{}] , key: [{}]",cacheName,key);
	Cache cache = manager.getCache(cacheName);
	if (cache != null) {
		cache.put(new Element(key, value));
	}
}
 
Example 11
Source File: CaseServlet.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Cache cache = cacheManager.getCache("testCache");

    String objectKey = "dataKey";

    Element el = new Element(objectKey, "2");

    // EhcacheOperateElementInterceptor
    cache.put(el);

    // EhcacheOperateObjectInterceptor
    cache.get(objectKey);

    // EhcacheOperateAllInterceptor
    cache.putAll(Arrays.asList(new Element[] {el}));

    // EhcacheLockInterceptor
    try {
        boolean success = cache.tryReadLockOnKey(objectKey, 300);
    } catch (InterruptedException e) {
    } finally {
        cache.releaseReadLockOnKey(objectKey);
    }

    // EhcacheCacheNameInterceptor
    cacheManager.addCacheIfAbsent("testCache2");

    Cache cloneCache = cacheManager.getCache("testCache2");

    // EhcacheOperateElementInterceptor
    cloneCache.put(el);

    PrintWriter printWriter = resp.getWriter();
    printWriter.write("success");
    printWriter.flush();
    printWriter.close();
}
 
Example 12
Source File: TestHtmlReport.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/** Test.
 * @throws IOException e */
@Test
public void testCache() throws IOException {
	final String cacheName = "test 1";
	final CacheManager cacheManager = CacheManager.getInstance();
	cacheManager.addCache(cacheName);
	// test empty cache name in the cache keys link:
	// cacheManager.addCache("") does nothing, but cacheManager.addCache(new Cache("", ...)) works
	cacheManager.addCache(new Cache("", 1000, true, false, 10000, 10000, false, 10000));
	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);
	}
}
 
Example 13
Source File: EhcacheImpl.java    From framework with Apache License 2.0 5 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author 王伟<br>
 * @taskId <br>
 * @param nodeName
 * @param expireTimes
 * @param node <br>
 */
@Override
public <T> void putNode(final String nodeName, final int expireTimes, final Map<String, T> node) {
    if (MapUtils.isNotEmpty(node)) {
        Cache cache = getCache(nodeName, expireTimes, 0);
        for (Entry<String, T> entry : node.entrySet()) {
            cache.put(new Element(entry.getKey(), entry.getValue()));
        }
    }
}
 
Example 14
Source File: EhCacheUtil.java    From zheng with MIT License 5 votes vote down vote up
/**
 * 新增缓存记录
 * @param cacheName
 * @param key
 * @param value
 */
public static void put(String cacheName, String key, Object value) {
    Cache cache = getCache(cacheName);
    if (null != cache) {
        Element element = new Element(key, value);
        cache.put(element);
    }
}
 
Example 15
Source File: DavResourceFactoryImpl.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Puts an entry in the cache
 * 
 * @param session The curent DAV session
 * @param resource The entry to be cached
 */
public void putInCache(DavSession session, DavResource resource) {
	try {
		ContextProperties config = Context.get().getProperties();
		if ("true".equals(config.getProperty("webdav.usecache"))) {
			// Initialize the collection of children
			Cache cache = ((CacheManager) Context.get().getBean("DavCacheManager"))
					.getCache("dav-resources");
			Element element = new Element(session.getObject("id") + ";" + resource.getResourcePath(), resource);
			cache.put(element);
		}
	} catch (Throwable t) {

	}
}
 
Example 16
Source File: CachePlugin.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
public static void put(String key, Object value) {
    Cache cache = cacheManager.getCache(Constants.CACHE_NAME);
    if (cache != null) {
        Element el = new Element(key, value);
        cache.put(el);
    }
}
 
Example 17
Source File: EhcacheTest.java    From kylin with Apache License 2.0 4 votes vote down vote up
@Test
public void basicTest() throws InterruptedException {
    System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M");

    Configuration conf = new Configuration();
    conf.setMaxBytesLocalHeap("100M");
    CacheManager cacheManager = CacheManager.create(conf);

    //Create a Cache specifying its configuration.
    Cache testCache = //Create a Cache specifying its configuration.
            new Cache(new CacheConfiguration("test", 0).//
                    memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU).//
                    eternal(false).//
                    timeToIdleSeconds(86400).//
                    diskExpiryThreadIntervalSeconds(0).//
                    //maxBytesLocalHeap(1000, MemoryUnit.MEGABYTES).//
                    persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.NONE)));

    cacheManager.addCache(testCache);

    System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M");
    byte[] blob = new byte[(1024 * 80 * 1024)];//400M
    Random random = new Random();
    for (int i = 0; i < blob.length; i++) {
        blob[i] = (byte) random.nextInt();
    }

    //        List<String> manyObjects = Lists.newArrayList();
    //        for (int i = 0; i < 10000; i++) {
    //            manyObjects.add(new String("" + i));
    //        }
    //        testCache.put(new Element("0", manyObjects));

    testCache.put(new Element("1", blob));
    System.out.println(testCache.get("1") == null);
    System.out.println(testCache.getSize());
    System.out.println(testCache.getStatistics().getLocalHeapSizeInBytes());
    System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M");

    blob = new byte[(1024 * 80 * 1024)];//400M
    for (int i = 0; i < blob.length; i++) {
        blob[i] = (byte) random.nextInt();
    }

    testCache.put(new Element("2", blob));
    System.out.println(testCache.get("1") == null);
    System.out.println(testCache.get("2") == null);
    System.out.println(testCache.getSize());
    System.out.println(testCache.getStatistics().getLocalHeapSizeInBytes());
    System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M");

    blob = new byte[(1024 * 80 * 1024)];//400M
    for (int i = 0; i < blob.length; i++) {
        blob[i] = (byte) random.nextInt();
    }
    testCache.put(new Element("3", blob));
    System.out.println(testCache.get("1") == null);
    System.out.println(testCache.get("2") == null);
    System.out.println(testCache.get("3") == null);
    System.out.println(testCache.getSize());
    System.out.println(testCache.getStatistics().getLocalHeapSizeInBytes());
    System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M");

    cacheManager.shutdown();
}
 
Example 18
Source File: EhcacheApiTest.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
/**
 * 使用Ehcache默认配置(classpath下的ehcache.xml)获取单例的CacheManager实例
 */
@Test
public void operation() {
	CacheManager manager = CacheManager.newInstance("src/test/resources/ehcache/ehcache.xml");

	// 获得Cache的引用
	Cache cache = manager.getCache("users");

	// 将一个Element添加到Cache
	cache.put(new Element("key1", "value1"));

	// 获取Element,Element类支持序列化,所以下面两种方法都可以用
	Element element1 = cache.get("key1");
	// 获取非序列化的值
	System.out.println("key=" + element1.getObjectKey() + ", value=" + element1.getObjectValue());
	// 获取序列化的值
	System.out.println("key=" + element1.getKey() + ", value=" + element1.getValue());

	// 更新Cache中的Element
	cache.put(new Element("key1", "value2"));
	Element element2 = cache.get("key1");
	System.out.println("key=" + element2.getObjectKey() + ", value=" + element2.getObjectValue());

	// 获取Cache的元素数
	System.out.println("cache size:" + cache.getSize());

	// 获取MemoryStore的元素数
	System.out.println("MemoryStoreSize:" + cache.getMemoryStoreSize());

	// 获取DiskStore的元素数
	System.out.println("DiskStoreSize:" + cache.getDiskStoreSize());

	// 移除Element
	cache.remove("key1");
	System.out.println("cache size:" + cache.getSize());

	// 关闭当前CacheManager对象
	manager.shutdown();

	// 关闭CacheManager单例实例
	CacheManager.getInstance().shutdown();
}
 
Example 19
Source File: EhcacheTest.java    From blog with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static void main(String[] args) {
	try {

		// 创建一个CacheManager实例
		CacheManager manager = new CacheManager();
		// 增加一个cache
		manager.addCache("cardCache");
		// 获取所有cache名称
		String[] cacheNamesForManager = manager.getCacheNames();
		int iLen = cacheNamesForManager.length;
		System.out.println("缓存名称列表:----------------------------");
		for (int i = 0; i < iLen; i++) {
			System.out.println(cacheNamesForManager[i].toString());
		}

		// 获取cache对象
		Cache cache = manager.getCache("cardCache");
		// create
		Element element = new Element("username", "howsky");
		cache.put(element);

		// get
		Element element_get = cache.get("username");
		Object value = element_get.getObjectValue();
		System.out.println(value.toString());
		
		Element element_get2 = cache.get("username");
		System.out.println(element_get2==element_get);

		// update
		cache.put(new Element("username", "howsky.net"));
		// get
		Element element_new = cache.get("username");
		
		System.out.println(element_new==element_get);
		
		Object value_new = element_new.getObjectValue();
		System.out.println(value_new.toString());

		cache.remove("username");

		// 移除cache
		manager.removeCache("cardCache");

		// 关闭CacheManager
		manager.shutdown();

	} catch (Exception e) {

		System.out.println(e.getMessage());

	}
}
 
Example 20
Source File: EhcacheTest.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
@Test
public void basicTest() throws InterruptedException {
    System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M");

    Configuration conf = new Configuration();
    conf.setMaxBytesLocalHeap("100M");
    CacheManager cacheManager = CacheManager.create(conf);

    //Create a Cache specifying its configuration.
    Cache testCache = //Create a Cache specifying its configuration.
            new Cache(new CacheConfiguration("test", 0).//
                    memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU).//
                    eternal(false).//
                    timeToIdleSeconds(86400).//
                    diskExpiryThreadIntervalSeconds(0).//
                    //maxBytesLocalHeap(1000, MemoryUnit.MEGABYTES).//
                    persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.NONE)));

    cacheManager.addCache(testCache);

    System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M");
    byte[] blob = new byte[(1024 * 80 * 1024)];//400M
    Random random = new Random();
    for (int i = 0; i < blob.length; i++) {
        blob[i] = (byte) random.nextInt();
    }

    //        List<String> manyObjects = Lists.newArrayList();
    //        for (int i = 0; i < 10000; i++) {
    //            manyObjects.add(new String("" + i));
    //        }
    //        testCache.put(new Element("0", manyObjects));

    testCache.put(new Element("1", blob));
    System.out.println(testCache.get("1") == null);
    System.out.println(testCache.getSize());
    System.out.println(testCache.getStatistics().getLocalHeapSizeInBytes());
    System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M");

    blob = new byte[(1024 * 80 * 1024)];//400M
    for (int i = 0; i < blob.length; i++) {
        blob[i] = (byte) random.nextInt();
    }

    testCache.put(new Element("2", blob));
    System.out.println(testCache.get("1") == null);
    System.out.println(testCache.get("2") == null);
    System.out.println(testCache.getSize());
    System.out.println(testCache.getStatistics().getLocalHeapSizeInBytes());
    System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M");

    blob = new byte[(1024 * 80 * 1024)];//400M
    for (int i = 0; i < blob.length; i++) {
        blob[i] = (byte) random.nextInt();
    }
    testCache.put(new Element("3", blob));
    System.out.println(testCache.get("1") == null);
    System.out.println(testCache.get("2") == null);
    System.out.println(testCache.get("3") == null);
    System.out.println(testCache.getSize());
    System.out.println(testCache.getStatistics().getLocalHeapSizeInBytes());
    System.out.println("runtime used memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024 + "M");

    cacheManager.shutdown();
}