方法返回的值可以分配给常量吗?



我想在 SpringBoot 中格式化一些文件,每个文件一个请求。对于每个请求,我必须调用getOutputFolder(dirName(方法来获取输出路径,以便将文件保存在预期的路径中,但我的解决方案带来了高昂的开销成本。我想定义一个常量,然后当我必须调用函数时,我改为调用它。但我觉得这似乎是错误的,或者至少是一种偷偷摸摸的方式。有没有更好的方法来解决这个问题?

private static final String OUTPUT_FOLDER_PATH = getOutputFolderPath();
private String getOutputFolder(String dirName) {
String pathStr = getOutputFolderPath() + dirName + File.separator + "submit" + File.separator;
Path outputDirPath = Paths.get(pathStr);
Path path = null;
boolean dirExists = Files.exists(outputDirPath);
if (!dirExists) {
try {
path = Files.createDirectories(outputDirPath);
} catch (IOException io) {
logger.error("Error occur when create the folder at: {}", pathStr);
}
}
return dirExists ? pathStr : Objects.requireNonNull(path).toString();
}

你可能想看看jcache。

为此,您需要将其安装到Spring Boot项目中。

implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'javax.cache:cache-api:1.1.0'
// or the maven equivalent if you are using maven

然后创建一个org.springframework.cache.CacheManagerBean 来配置缓存。

@Bean
public CacheManager cacheManager() {
CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager cacheManager = cachingProvider.getCacheManager();
// The class arguments is <String, String> because the method to cache accepts a String and returns a String
// just explore this object for the config you need.
MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
String cacheName = "OUTPUT_FOLDER_CACHE";
cacheManager.createCache(cacheName, configuration);
return cacheManager;
}

设置后,现在可以批注要缓存的方法。

@Cacheable(
cacheNames = { "OUTPUT_FOLDER_CACHE" }, // The same string in config
unless = "#result == null" // Dont' cache null result; or do, if you need it.
)
String getOutputFolder(String dirName) {
// method contents...
}

正确配置后:该方法将返回缓存值(如果存在(,或者运行实际方法,缓存结果,如果缓存值不存在,则返回结果。

您可以使用 ThreadLocal 解决此问题。 线程本地可以存储价值,您可以为自己所用。假设如果你的getOutputFolderPath((对于不同的请求是不同的,那么你可以 在服务器上调度新请求时存储 getOutputFolderPath(( 值,您可以实时执行请求之前的所有操作。

请参阅线程本地文档

@Service
public class FileSaveService {
private static final ThreadLocal<String> path=new ThreadLocal<>();
@PostConstruct
public void init() {
setPath(getOutputFolderPath());
}
public void setPath(String pathString) {
path.set(pathString);
}
public String getPath() {
if(path.get() == null) return getOutputFolderPath();
return path.get();
}
@PreDestroy
public void destroy() {
path.remove();
}
}

最新更新