LOAD and CACHE application-scoped data with @Singleton and @Stateless

前端 未结 1 811
借酒劲吻你
借酒劲吻你 2020-12-01 23:01

I\'m looking for an elegant solutions to the old problem of loading and caching static, shared data at application startup (with an infinite lifetime). <

相关标签:
1条回答
  • 2020-12-01 23:45

    Well, I've made some tests, and I've also tried the @Decorator way. This still seems to be the best one.

    @Entity bean and @Stateless bean are the same of the question, while I've changed the @Singleton bean as follows, also adding the classic timed cache:

    @Singleton
    public class RoomsCached {
    
        @Inject
        Rooms rooms;
    
        private List<Room> cachedRooms; 
        private long timeout = 86400000L; // reload once a day
        private long lastUpdate;    
    
    
        public List<Room> getCachedRooms() {
            initCache();
            return cachedRooms;
        }
    
        public void initCache() {
            if (cachedRooms == null || expired()) {
                cachedRooms = Collections.unmodifiableList(rooms.findAll());
                lastUpdate  = System.currentTimeMillis();
            }
        }        
    
        private boolean expired() { 
            return System.currentTimeMillis() > lastUpdate + timeout; 
        }
    
    }
    

    No need to @PostConstruct, nor to @EJB, no sync issues with the underlying, @inject-ed @Stateless bean.

    It's working great.

    0 讨论(0)
提交回复
热议问题