|
在最后,我们需要ServicePublisher来观察Spring容器的生命周期,并且在我们的缓存中发布或移除服务定义:
这段代码显示ServicePublisher在Spring上下文刷新时(如应用补布署时)如何处理: private void contextRefreshed() throws Exception { logger.info("context refreshed");
String[] names = context .getBeanNamesForType(AutoDiscoveredServiceExporter.class); logger.info("exporting services:" + names.length); for (int i = 0; i < names.length; i++) { String serviceUrl = makeUrl(names[i]); try { Set services = (Set) cache.get(SERVICE_PREFIX + names[i], SERVICE_KEY); if (services == null) services = new HashSet(); services.add(serviceUrl); cache.put(SERVICE_PREFIX + names[i], SERVICE_KEY, services); logger.info("added:" + serviceUrl); } catch (Exception ex) { logger.error("exception adding service:", ex); } } 如你所见,发布器简单的遍历通过缓存服务描述导出的服务列表并增加定义到缓存中。我们的缓存设计成路径包含服务名,他的URL列表存储在一个Set对象中。将服务名作为路径的一部分对JBoss Cache实现来说是重要的因为他是基于路径来创建和释放事务锁。这种方式下,对服务A的更新不会干扰对服务B的更新因为他们被映射到不同的路径:/some/prefix/serviceA/key=(list of URLs) and /some/prefix/serviceB/key=(list of URLs)。 移除服务定义的代码是类似的。
现在我们转到客户端。我们需要一个缓存实现来与服务端共享: LocalJBossCacheServiceImpl保存着来自与服务端相同的custom-cache-service.xml配置的JBoss Cache引用: public LocalJBossCacheServiceImpl() throws Exception { super(); cache = new TreeCache(); PropertyConfigurator config = new PropertyConfigurator(); config.configure(cache, "app/context/custom-cache-service.xml"); } 这个缓存定义文件包含了Jgroups层的配置,允许所有缓存成员通过UDP多播来定位彼此。
|