我将通过单例模式运行套接字服务器,因为我有多个线程,每次调用它时,我想使用相同的套接字服务器。这是 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 ;
}
}
这是套接字端口的枚举。
公共(public)枚举 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 ;
}
关于java - 通过 Singleton 的 Socket 服务器,使用属性文件中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59927346/