Vaadin 8-应用程序级缓存 [英] Vaadin 8 - application-wide cache

查看:54
本文介绍了Vaadin 8-应用程序级缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Vaadin 8项目中,每当应用程序启动和运行时,我都会将一些对象保留在主存储器中.

In my Vaadin 8 project, there are some objects that I keep in the main memory whenever the application is up&running.

为了提高内存效率,我希望为所有用户保留此缓存,而不是为每个用户保留单独的缓存.因此,缓存应该针对每个应用程序,即这些对象的单个集合,而不是针对每个会话.

For memory efficiency, I'm looking to keep this cache for all users-- not a separate cache for each user. So the cache should be per application, i.e., a single set of these objects, and NOT per session.

在Vaadin 8中如何执行此操作?请注意-该系统中没有Spring,因此无法在Spring上执行.

How to do this in Vaadin 8? Please note - there's no Spring in this system, so doing it on Spring is not an option.

请原谅.在Vaadin/网络开发人员上还不那么精明.

Excuse if a naïve question. Not yet that savvy on Vaadin/web dev.

推荐答案

对于应用程序级缓存,只需创建一个带有公共静态缓存的类,您就可以从任何地方访问该类.每个UI和会话的静态对象都是相同的.

For a application wide cache, just create a class with a public static cache that you can access from everywhere. The static object will be the same for every UI and session.

由于您未指定要缓存的内容,所以我想要缓存由您制作的自定义对象,以用于某种服务器端逻辑.

Since you didn't specify what do you want to cache, I suppose you want to cache custom objects made by you to use for some sort of server side logic.

要在纯Java中这样做,您可以创建一个简单的哈希图以用作缓存.一个非常简单的例子是:

To do so in plain java, you can create a simple hashmap to use as cache. A VERY simple example would be:

public class GlobalCache {

    private static ConcurrentHashMap<String, Object> cacheMap = new ConcurrentHashMap<>();

    public static Object getObject(String key, Function<String, Object> creator) {
        return cacheMap.computeIfAbsent(key, creator);
    }

}

那不是一个好的缓存,因为它不会使条目无效.如果可以添加任何库,则应添加Guava.番石榴提供了一个很棒的缓存实现,您可以使用:

That wouldn't be a good cache since it won't invalidate its entries. If you can add any libraries, you should add Guava. Guava provides a great cache implementation that you can use:

//Add this to your gradle:
dependencies {
    implementation group: 'com.google.guava', name: 'guava', version: '24.1-jre'
}

//And this will become your code
public class GlobalCache {
    private static Cache<String, Object> cache = 
        CacheBuilder.newBuilder().maximumSize(100).expireAfterWrite(5, TimeUnit.MINUTES).build();

    public static Object getObject(String key, Callable<? extends Object> creator) throws ExecutionException {
        return cache.get(key, creator);
    }
}

这篇关于Vaadin 8-应用程序级缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆