Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

Spring java项目对外提供服务和java进程启动时bean,内部缓存加载的先后关系?

Spring java项目对外提供服务有这么几种,一种是web服务,譬如tomcat,一种是RPC服务,譬如dubbo,thrift。总的来说就是对外开放某个/些端口,接收请求。

Spring工程项目启动时,bean会加载,内部的一些类成员缓存,譬如guava的CacheBuilder.newBuilder().build(){},会初始化。

Spring或者java是如何保证bean加载完,缓存加载完后才对外提供服务的呢?

打个比方,下面是一个@Service注解的类的类成员,初始化时会远程调用来加载缓存,如何保证这个缓存加载完成后,该java进程才对外服务呢?

    private LoadingCache<String, Set<Long>> mycache = CacheBuilder.newBuilder()
                .expireAfterWrite(6, TimeUnit.MINUTES)
                .refreshAfterWrite(5, TimeUnit.MINUTES)
                .build(new CacheLoader<String, Set<Long>>() {
                    @Override
                    public Set<Long> load(String key) throws Exception {
                        Set<Long> resultSet = myFeign.callRemote(param);
                        return resultSet;
                    }

                    @Override
                    public ListenableFuture<Set<Long>> reload(final String key, Set<Long> oldValue) throws Exception {
                        return listeningThreadPool.getListeningExecutor().submit(new Callable<Set<Long>>() {
                            @Override
                            public Set<Long> call() throws Exception {
                                return load(key);
                            }
                        });
                    }
                });
               

~


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

一般来说,对外服务的控制类Controller也是bean,所以没有这些问题,如果controller依赖到一个bean,那么这个bean肯定会比controller更早实例化。

其次,不了解你的缓存机制,如果你需要创建实例之后调用某个方法加载缓存,可以用BeanFactory创建bean的实例。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...