publicvoiddoSaveProperties(long version) { if(version < lastCacheChanged.get()){ return; } if (file == null) { return; } PropertiesnewProperties=newProperties(); // 保存之前先读取一遍,防止多个注册中心之间冲突 InputStreamin=null; try { if (file.exists()) { in = newFileInputStream(file); newProperties.load(in); } } catch (Throwable e) { logger.warn("Failed to load registry store file, cause: " + e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.warn(e.getMessage(), e); } } } // 保存 try { newProperties.putAll(properties); Filelockfile=newFile(file.getAbsolutePath() + ".lock"); if (!lockfile.exists()) { lockfile.createNewFile(); } RandomAccessFileraf=newRandomAccessFile(lockfile, "rw"); try { FileChannelchannel= raf.getChannel(); try { FileLocklock= channel.tryLock(); if (lock == null) { thrownewIOException("Can not lock the registry cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.registry.file=xxx.properties"); } // 保存 try { if (! file.exists()) { file.createNewFile(); } FileOutputStreamoutputFile=newFileOutputStream(file); try { newProperties.store(outputFile, "Dubbo Registry Cache"); } finally { outputFile.close(); } } finally { lock.release(); } } finally { channel.close(); } } finally { raf.close(); } } catch (Throwable e) { if (version < lastCacheChanged.get()) { return; } else { registryCacheExecutor.execute(newSaveProperties(lastCacheChanged.incrementAndGet())); } logger.warn("Failed to save registry store file, cause: " + e.getMessage(), e); } }
如果是两个不同的注册中心,不能使用一个缓存文件。 值得注意一点的是,多个dubbo服务公用一个cache文件的时候,如果一起启动,可能会出现Failed to load registry store File 这类异常信息, 这是因为当时该文件其他服务占用了。这种情况开发环境比较多,可以无视掉。因为会重复去注册的,下面会说明, 但是尽量还是手动指定注册缓存文件比较好。尽量不使用同一个缓存文件。