java - 通过 Singleton 使用属性文件中的参数的 Socket 服务器
问题描述
我将通过单例模式运行 Socket Server,因为我有多个线程,并且每次调用它时,我都想使用同一个套接字服务器。这是SocketSingleton.java
类:
public class SocketSingleton {
private static ServerSocket serverSocket = null;
private SocketSingleton() {}
public static synchronized ServerSocket getServerSocket() throws IOException {
PropertiesKey prop = new PropertiesKey();
if (serverSocket == null) {
serverSocket = new ServerSocket(prop.getSocketPort());
}
return serverSocket;
}
}
但我注意到我应该从configuration.properties
喜欢SOCKET_PORT=2203
我可以使用下面的代码从配置中获取值
public class PropertiesAlgorithmImpl implements PropertiesAlgorithm {
private static Properties defaultProps = new Properties();
static {
try {
String propertiesDirectory = "src/main/resources/configuration.properties";
FileInputStream in = new FileInputStream(propertiesDirectory);
if (in == null) {
System.out.println("Sorry, unable to find " + propertiesDirectory);
}
defaultProps.load(in);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getValuesFromProperties(String key) {
if (defaultProps.getProperty(key) != null) {
return defaultProps.getProperty(key);
}
return "Sorry, unable to find " + key ;
}
}
这是一个 Socket Port 的枚举。
public enum CONFIG { SOCKET_PORT}
public class PropertiesKey {
private PropertiesAlgorithm propertiesAlgorithm;
public int getSocketPort(){
propertiesAlgorithm = new PropertiesAlgorithmImpl();
return Integer.parseInt(propertiesAlgorithm.getValuesFromProperties(CONFIG.SOCKET_PORT.name()));
}
在 SocketSingleton 类中,我这样调用套接字端口:
serverSocket = new ServerSocket(prop.getSocketPort());
我无法从中获取套接字端口参数的可能原因是什么configuration.properties
?
解决方案
我用输入流修复了下面的类,它起作用了:
public class PropertiesAlgorithmImpl implements PropertiesAlgorithm {
private static final Logger logger = LoggerFactory.getLogger(PropertiesAlgorithmImpl.class);
private static Properties defaultProps = new Properties();
static {
String propertiesDirectory = "config.properties";
try (InputStream input = PropertiesAlgorithmImpl.class.getClassLoader().getResourceAsStream(propertiesDirectory)) {
if (input == null) {
logger.info("Sorry, unable to find " + propertiesDirectory);
}
defaultProps.load(input);
input.close();
} catch (Exception e) { logger.info(String.valueOf(e.getStackTrace())); }
}
public String getValuesFromProperties(String key) {
if (defaultProps.getProperty(key) != null) {
return defaultProps.getProperty(key);
}
logger.info("Sorry, unable to find " + key);
return "Sorry, unable to find " + key ;
}
推荐阅读
- prometheus - Prometheus 从 InfluxDB 远程读取不返回任何数据
- java - 如何在单独的 docker Hazelcast 节点(嵌入在应用程序中的主节点)禁用数据的反序列化过程
- java - 为什么在使用 Gson.asString 时出现 java.lang.UnsupportedOperationException?
- python-3.x - 日志未显示在 AWS Cloudwatch 中
- sql - 如何修复 SQL Server 中的错误编码?
- powershell - 如何通过 SlackAPI 和 PSSlack 模块更改 Slack 的详细信息
- parsing - 将具有不同 col/rowspans 的电子表格转换为 HTML 表格
- css - 如何使用 css 为一系列类定义样式(.progress-10 到 .progress-40)
- swift - 理解 Swift 中的实例化 - OOP
- javascript - 从受保护的页面下载文件