首页 > 解决方案 > 通过 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

标签: javasockets

解决方案


我用输入流修复了下面的类,它起作用了:

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 ;
}

推荐阅读