新功能点:所有配置项支持从环境变量里读取,方便Docker镜像部署

This commit is contained in:
陈精华 2019-10-25 13:59:29 +08:00 committed by kl
parent 8fdf462c6c
commit fa7241bd4e
6 changed files with 75 additions and 48 deletions

View File

@ -15,6 +15,7 @@ package org.artofsolving.jodconverter.office;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.io.FileReader;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
@ -26,6 +27,8 @@ import com.sun.star.uno.UnoRuntime;
public class OfficeUtils { public class OfficeUtils {
public static final String SERVICE_DESKTOP = "com.sun.star.frame.Desktop"; public static final String SERVICE_DESKTOP = "com.sun.star.frame.Desktop";
public static final String OFFICE_HOME_KEY = "office.home";
public static final String DEFAULT_OFFICE_HOME_VALUE = "default";
private OfficeUtils() { private OfficeUtils() {
throw new AssertionError("utility class must not be instantiated"); throw new AssertionError("utility class must not be instantiated");
@ -69,9 +72,11 @@ public class OfficeUtils {
try { try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(customizedConfigPath)); BufferedReader bufferedReader = new BufferedReader(new FileReader(customizedConfigPath));
properties.load(bufferedReader); properties.load(bufferedReader);
restorePropertiesFromEnvFormat(properties);
} catch (Exception e) {} } catch (Exception e) {}
if (properties.getProperty("office.home") != null) { String officeHome = properties.getProperty(OFFICE_HOME_KEY);
return new File(properties.getProperty("office.home")); if (officeHome != null && !DEFAULT_OFFICE_HOME_VALUE.equals(officeHome)) {
return new File(officeHome);
} }
if (PlatformUtils.isWindows()) { if (PlatformUtils.isWindows()) {
// %ProgramFiles(x86)% on 64-bit machines; %ProgramFiles% on 32-bit ones // %ProgramFiles(x86)% on 64-bit machines; %ProgramFiles% on 32-bit ones
@ -147,4 +152,32 @@ public class OfficeUtils {
return configFilePath; return configFilePath;
} }
/**
* SpringBoot application.properties 支持从环境变量获取值
* @param properties
*/
public synchronized static void restorePropertiesFromEnvFormat(Properties properties) {
Iterator<Map.Entry<Object, Object>> iterator = properties.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Object, Object> entry = iterator.next();
String key = entry.getKey().toString();
String value = entry.getValue().toString();
if (value.trim().startsWith("${") && value.trim().endsWith("}")) {
int beginIndex = value.indexOf(":");
if (beginIndex < 0) {
beginIndex = value.length() - 1;
}
int endIndex = value.length() - 1;
String envKey = value.substring(2, beginIndex);
String envValue = System.getenv(envKey);
if (envValue == null || "".equals(envValue.trim())) {
value = value.substring(beginIndex + 1, endIndex);
} else {
value = envValue;
}
properties.setProperty(key, value);
}
}
}
} }

View File

@ -1,5 +1,5 @@
#######################################不可动态配置,需要重启生效####################################### #######################################不可动态配置,需要重启生效#######################################
server.port = 8012 server.port = ${KK_SERVER_PORT:8012}
spring.http.encoding.charset = utf8 spring.http.encoding.charset = utf8
## Freemarker 配置 ## Freemarker 配置
spring.freemarker.template-loader-path = classpath:/web/ spring.freemarker.template-loader-path = classpath:/web/
@ -19,37 +19,39 @@ spring.http.multipart.max-file-size=100MB
#文件资源路径默认为打包根路径下的file目录下 #文件资源路径默认为打包根路径下的file目录下
#file.dir = D:\\kkFileview\\ #file.dir = D:\\kkFileview\\
file.dir = ${KK_FILE_DIR:default}
#openoffice home路径 #openoffice home路径
#office.home = C:\\Program Files (x86)\\OpenOffice 4 #office.home = C:\\Program Files (x86)\\OpenOffice 4
office.home = ${KK_OFFICE_HOME:default}
#缓存实现类型不配默认为内嵌RocksDB实现可配置为redis(type = redis)实现需要配置spring.redisson.address等参数和 JDK 内置对象实现type = jdk, #缓存实现类型不配默认为内嵌RocksDB(type = default)实现可配置为redis(type = redis)实现需要配置spring.redisson.address等参数和 JDK 内置对象实现type = jdk,
#cache.type = redis cache.type = ${KK_CACHE_TYPE:default}
#redis连接 #redis连接只有当cache.type = redis时才有用
#spring.redisson.address = 192.168.1.204:6379 spring.redisson.address = ${KK_SPRING_REDISSON_ADDRESS:127.0.0.1:6379}
#spring.redisson.password = xxx spring.redisson.password = ${KK_SPRING_REDISSON_PASSWORD:123456}
cache.clean.enabled = true #缓存是否自动清理 true 为开启,注释掉或其他值都为关闭
cache.clean.enabled = ${KK_CACHE_CLEAN_ENABLED:true}
#缓存自动清理时间cache.clean.enabled = true时才有用cron表达式基于Quartz cron #缓存自动清理时间cache.clean.enabled = true时才有用cron表达式基于Quartz cron
cache.clean.cron = 0 0 3 * * ? cache.clean.cron = ${KK_CACHE_CLEAN_CRON:0 0 3 * * ?}
#######################################可在运行时动态配置####################################### #######################################可在运行时动态配置#######################################
#提供预览服务的地址默认从请求url读如果使用nginx等反向代理需要手动设置 #提供预览服务的地址默认从请求url读如果使用nginx等反向代理需要手动设置
#base.url = https://file.keking.cn #base.url = https://file.keking.cn
base.url = ${KK_BASE_URL:default}
#是否启用缓存 #是否启用缓存
cache.enabled = true cache.enabled = ${KK_CACHE_ENABLED:true}
#文本类型,默认如下,可自定义添加 #文本类型,默认如下,可自定义添加
#simText = txt,html,xml,properties,md,java,py,c,cpp,sql simText = ${KK_SIMTEXT:txt,html,htm,asp,jsp,xml,json,properties,md,gitignore,,java,py,c,cpp,sql,sh,bat,m,bas,prg,cmd}
#多媒体类型,默认如下,可自定义添加 #多媒体类型,默认如下,可自定义添加
#media = mp3,wav,mp4,flv media = ${KK_MEDIA:mp3,wav,mp4,flv}
#文件转换编码,默认根据操作系统获取
#converted.file.charset = GBK
#office类型文档(word ppt)样式,默认为图片(image)可配置为pdf预览时也有按钮切换 #office类型文档(word ppt)样式,默认为图片(image)可配置为pdf预览时也有按钮切换
#office.preview.type = pdf office.preview.type = ${KK_OFFICE_PREVIEW_TYPE:image}
#预览源为FTP时 FTP用户名可在ftp url后面加参数ftp.username=ftpuser指定不指定默认用配置的 #预览源为FTP时 FTP用户名可在ftp url后面加参数ftp.username=ftpuser指定不指定默认用配置的
ftp.username = ftpuser ftp.username = ${KK_FTP_USERNAME:ftpuser}
#预览源为FTP时 FTP密码可在ftp url后面加参数ftp.password=123456指定不指定默认用配置的 #预览源为FTP时 FTP密码可在ftp url后面加参数ftp.password=123456指定不指定默认用配置的
ftp.password = 123456 ftp.password = ${KK_FTP_PASSWORD:123456}
#预览源为FTP时, FTP连接默认ControlEncoding(根据FTP服务器操作系统选择Linux一般为UTF-8Windows一般为GBK)可在ftp url后面加参数ftp.control.encoding=UTF-8指定不指定默认用配置的 #预览源为FTP时, FTP连接默认ControlEncoding(根据FTP服务器操作系统选择Linux一般为UTF-8Windows一般为GBK)可在ftp url后面加参数ftp.control.encoding=UTF-8指定不指定默认用配置的
ftp.control.encoding = UTF-8 ftp.control.encoding = ${KK_FTP_CONTROL_ENCODING:UTF-8}

View File

@ -17,7 +17,6 @@ public class ConfigConstants {
private static Boolean cacheEnabled; private static Boolean cacheEnabled;
private static String[] simText = {}; private static String[] simText = {};
private static String[] media = {}; private static String[] media = {};
private static String convertedFileCharset;
private static String officePreviewType; private static String officePreviewType;
private static String ftpUsername; private static String ftpUsername;
private static String ftpPassword; private static String ftpPassword;
@ -25,6 +24,8 @@ public class ConfigConstants {
private static String fileDir = OfficeUtils.getHomePath() + File.separator + "file" + File.separator; private static String fileDir = OfficeUtils.getHomePath() + File.separator + "file" + File.separator;
private static String baseUrl; private static String baseUrl;
public static final String DEFAULT_FILE_DIR_VALUE = "default";
public static Boolean isCacheEnabled() { public static Boolean isCacheEnabled() {
return cacheEnabled; return cacheEnabled;
} }
@ -49,14 +50,6 @@ public class ConfigConstants {
ConfigConstants.media = media; ConfigConstants.media = media;
} }
public static String getConvertedFileCharset() {
return convertedFileCharset;
}
public static void setConvertedFileCharset(String convertedFileCharset) {
ConfigConstants.convertedFileCharset = convertedFileCharset;
}
public static String getOfficePreviewType() { public static String getOfficePreviewType() {
return officePreviewType; return officePreviewType;
} }
@ -98,13 +91,12 @@ public class ConfigConstants {
} }
public static void setBaseUrl(String baseUrl) { public static void setBaseUrl(String baseUrl) {
// 不以'/'结尾的加上'/' ConfigConstants.baseUrl = baseUrl;
ConfigConstants.baseUrl = baseUrl.concat("/");
} }
@Value("${file.dir:default}") @Value("${file.dir:default}")
public void setFileDir(String fileDir) { public void setFileDir(String fileDir) {
if (!"default".equals(fileDir)) { if (!DEFAULT_FILE_DIR_VALUE.equals(fileDir.toLowerCase())) {
if (!fileDir.endsWith(File.separator)) { if (!fileDir.endsWith(File.separator)) {
fileDir = fileDir + File.separator; fileDir = fileDir + File.separator;
} }

View File

@ -5,7 +5,6 @@ import org.artofsolving.jodconverter.office.OfficeUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -24,14 +23,13 @@ public class ConfigRefreshComponent {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigRefreshComponent.class); private static final Logger LOGGER = LoggerFactory.getLogger(ConfigRefreshComponent.class);
public static final String DEFAULT_CACHE_ENABLED = "true"; public static final String DEFAULT_CACHE_ENABLED = "true";
public static final String DEFAULT_TXT_TYPE = "txt,html,xml,properties,md,java,py,c,cpp,sql"; public static final String DEFAULT_TXT_TYPE = "txt,html,htm,asp,jsp,xml,json,properties,md,gitignore,,java,py,c,cpp,sql,sh,bat,m,bas,prg,cmd";
public static final String DEFAULT_MEDIA_TYPE = "mp3,wav,mp4,flv"; public static final String DEFAULT_MEDIA_TYPE = "mp3,wav,mp4,flv";
public static final String DEFAULT_CONVERTER_CHARSET = System.getProperty("sun.jnu.encoding");
public static final String DEFAULT_FTP_USERNAME = null; public static final String DEFAULT_FTP_USERNAME = null;
public static final String DEFAULT_FTP_PASSWORD = null; public static final String DEFAULT_FTP_PASSWORD = null;
public static final String DEFAULT_FTP_CONTROL_ENCODING = "UTF-8"; public static final String DEFAULT_FTP_CONTROL_ENCODING = "UTF-8";
public static final String BASE_URL = null; public static final String DEFAULT_BASE_URL = "default";
@PostConstruct @PostConstruct
void refresh() { void refresh() {
@ -49,7 +47,6 @@ public class ConfigRefreshComponent {
Boolean cacheEnabled; Boolean cacheEnabled;
String[] textArray; String[] textArray;
String[] mediaArray; String[] mediaArray;
String convertedFileCharset;
String officePreviewType; String officePreviewType;
String ftpUsername; String ftpUsername;
String ftpPassword; String ftpPassword;
@ -60,28 +57,25 @@ public class ConfigRefreshComponent {
FileReader fileReader = new FileReader(configFilePath); FileReader fileReader = new FileReader(configFilePath);
BufferedReader bufferedReader = new BufferedReader(fileReader); BufferedReader bufferedReader = new BufferedReader(fileReader);
properties.load(bufferedReader); properties.load(bufferedReader);
OfficeUtils.restorePropertiesFromEnvFormat(properties);
cacheEnabled = new Boolean(properties.getProperty("cache.enabled", DEFAULT_CACHE_ENABLED)); cacheEnabled = new Boolean(properties.getProperty("cache.enabled", DEFAULT_CACHE_ENABLED));
text = properties.getProperty("simText", DEFAULT_TXT_TYPE); text = properties.getProperty("simText", DEFAULT_TXT_TYPE);
media = properties.getProperty("media", DEFAULT_MEDIA_TYPE); media = properties.getProperty("media", DEFAULT_MEDIA_TYPE);
convertedFileCharset = properties.getProperty("converted.file.charset", DEFAULT_CONVERTER_CHARSET);
officePreviewType = properties.getProperty("office.preview.type", OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_IMAGE); officePreviewType = properties.getProperty("office.preview.type", OfficeFilePreviewImpl.OFFICE_PREVIEW_TYPE_IMAGE);
ftpUsername = properties.getProperty("ftp.username", DEFAULT_FTP_USERNAME); ftpUsername = properties.getProperty("ftp.username", DEFAULT_FTP_USERNAME);
ftpPassword = properties.getProperty("ftp.password", DEFAULT_FTP_PASSWORD); ftpPassword = properties.getProperty("ftp.password", DEFAULT_FTP_PASSWORD);
ftpControlEncoding = properties.getProperty("ftp.control.encoding", DEFAULT_FTP_CONTROL_ENCODING); ftpControlEncoding = properties.getProperty("ftp.control.encoding", DEFAULT_FTP_CONTROL_ENCODING);
textArray = text.split(","); textArray = text.split(",");
mediaArray = media.split(","); mediaArray = media.split(",");
baseUlr = properties.getProperty("base.url", null); baseUlr = properties.getProperty("base.url", DEFAULT_BASE_URL);
ConfigConstants.setCacheEnabled(cacheEnabled); ConfigConstants.setCacheEnabled(cacheEnabled);
ConfigConstants.setSimText(textArray); ConfigConstants.setSimText(textArray);
ConfigConstants.setMedia(mediaArray); ConfigConstants.setMedia(mediaArray);
ConfigConstants.setConvertedFileCharset(convertedFileCharset);
ConfigConstants.setOfficePreviewType(officePreviewType); ConfigConstants.setOfficePreviewType(officePreviewType);
ConfigConstants.setFtpUsername(ftpUsername); ConfigConstants.setFtpUsername(ftpUsername);
ConfigConstants.setFtpPassword(ftpPassword); ConfigConstants.setFtpPassword(ftpPassword);
ConfigConstants.setFtpControlEncoding(ftpControlEncoding); ConfigConstants.setFtpControlEncoding(ftpControlEncoding);
if (baseUlr != null && !StringUtils.isEmpty(baseUlr)) { ConfigConstants.setBaseUrl(baseUlr);
ConfigConstants.setBaseUrl(baseUlr);
}
bufferedReader.close(); bufferedReader.close();
fileReader.close(); fileReader.close();
Thread.sleep(1000L); Thread.sleep(1000L);

View File

@ -1,7 +1,7 @@
package cn.keking.filters; package cn.keking.filters;
import cn.keking.config.ConfigConstants; import cn.keking.config.ConfigConstants;
import org.springframework.util.StringUtils; import cn.keking.config.ConfigRefreshComponent;
import javax.servlet.*; import javax.servlet.*;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -23,8 +23,12 @@ public class ChinesePathFilter implements Filter {
request.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8");
String baseUrl; String baseUrl;
if (ConfigConstants.getBaseUrl() != null) { String baseUrlTmp = ConfigConstants.getBaseUrl();
baseUrl = ConfigConstants.getBaseUrl(); if (baseUrlTmp != null && !ConfigRefreshComponent.DEFAULT_BASE_URL.equals(baseUrlTmp.toLowerCase())) {
if (!baseUrlTmp.endsWith("/")) {
baseUrlTmp = baseUrlTmp.concat("/");
}
baseUrl = baseUrlTmp;
} else { } else {
StringBuilder pathBuilder = new StringBuilder(); StringBuilder pathBuilder = new StringBuilder();
pathBuilder.append(request.getScheme()).append("://").append(request.getServerName()).append(":") pathBuilder.append(request.getScheme()).append("://").append(request.getServerName()).append(":")

View File

@ -25,6 +25,9 @@ import java.util.Map;
*/ */
@Component @Component
public class FileUtils { public class FileUtils {
public static final String DEFAULT_CONVERTER_CHARSET = System.getProperty("sun.jnu.encoding");
Logger log= LoggerFactory.getLogger(getClass()); Logger log= LoggerFactory.getLogger(getClass());
@Autowired @Autowired
@ -233,9 +236,8 @@ public class FileUtils {
*/ */
public void doActionConvertedFile(String outFilePath) { public void doActionConvertedFile(String outFilePath) {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
String charset = ConfigConstants.getConvertedFileCharset();
try (InputStream inputStream = new FileInputStream(outFilePath); try (InputStream inputStream = new FileInputStream(outFilePath);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset))){ BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, DEFAULT_CONVERTER_CHARSET))){
String line; String line;
while(null != (line = reader.readLine())){ while(null != (line = reader.readLine())){
if (line.contains("charset=gb2312")) { if (line.contains("charset=gb2312")) {