2021-10-27 周三

缘起

最近开始使用Java编写Redis的项目Jmedis,给项目实现了单例的配置文件读取。 废话少说,直接上代码。

设计思路

  1. 未读取配置文件时,则使用代码内默认值。
  2. 采用格式 type@key=value ,实现反射设置配置对象属性。
  3. 单例保证全局唯一,服务器启动后立马加载,保证在其他方法使用配置前加载完成。

代码实现

1
2
3
4
5
6
7
#格式 type@key=value
#数据库大小
int@dbSize=16
#缓冲区大小,默认4M
int@bufferSize=4096
#服务端密码
string@authPasswd=123456
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package org.mango.jmedis.config;


import org.mango.jmedis.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @Description 服务器配置
 * @Date 2021-10-23 14:53
 * @Created by mango
 */
public class ServerConf {

    private static Logger log = LoggerFactory.getLogger(ServerConf.class);


    // 单例
    private ServerConf(){}

    private static ServerConf serverConf;

    static{
        serverConf = new ServerConf();
    }

    public static ServerConf getConf(){
        return serverConf;
    }

    /**
     * 默认数据库大小
     */
    private Integer dbSize = 16;
    /**
     * 缓冲区大小,默认4M
     */
    private Integer bufferSize = 4 * 1024;
    /**
     * 数据库密码,默认为空
     */
    private String authPasswd = "";

    public Integer getDbSize() {
        return dbSize;
    }

    public void setDbSize(Integer dbSize) {
        this.dbSize = dbSize;
    }

    public Integer getBufferSize() {
        return bufferSize;
    }

    public void setBufferSize(Integer bufferSize) {
        this.bufferSize = bufferSize;
    }

    public String getAuthPasswd() {
        return authPasswd;
    }

    public void setAuthPasswd(String authPasswd) {
        this.authPasswd = authPasswd;
    }

    /**
     * 加载配置文件
     */
    public static void loadServerConf(String conf) {
        try {
            if (StringUtil.isNotBlank(conf)) {
                File confFile = new File(conf);
                if (confFile.exists() && confFile.isFile()) {
                    // 类型映射
                    Map<String,Class> typeMap = new HashMap<>();
                    typeMap.put("int",Integer.class);
                    typeMap.put("string",String.class);
                    typeMap.put("boolean",Boolean.class);
                    // 转换方法映射
                    Map<String,Method> parseMap = new HashMap<>();
                    parseMap.put("int",Integer.class.getMethod("parseInt",String.class));
                    parseMap.put("boolean",Boolean.class.getMethod("parseBoolean", String.class));
                    // 加载配置文件
                    Properties confProp = new Properties();
                    FileInputStream fis = new FileInputStream(confFile);
                    confProp.load(fis);
                    Set<String> propSet = confProp.stringPropertyNames();
                    for(String e : propSet){
                        // 类型
                        String type = e.split("@")[0];
                        // 属性名
                        String key = e.split("@")[1];
                        Method setMethod = getConf().getClass().getMethod(getSetMethodStr(key),typeMap.get(type));
                        if(null != setMethod){
                            Object value = confProp.get(e);
                            if(parseMap.containsKey(type)){
                                value = parseMap.get(type).invoke(value,value);
                            }
                            // 反射设置值
                            setMethod.invoke(getConf(),value);
                        }
                    }
                    //加载完成关闭文件流
                    fis.close();
                    log.info("load conf from file {} success,conf is {}", conf, getConf().toString());
                } else {
                    log.error("conf {} is not exists", conf);
                }
            } else {
                log.info("load default conf,conf is {}",getConf().toString());
            }
        }catch (Exception e){
            log.error("load conf error,{}",e.getMessage(),e);
        }
    }

    /**
     * 返回setMethod
     * @param prop
     * @return
     */
    private static String getSetMethodStr(String prop){
        return "set" + prop.substring(0,1).toUpperCase() + prop.substring(1);
    }


    @Override
    public String toString() {
        return "ServerConf{" +
                "dbSize=" + dbSize +
                ", bufferSize=" + bufferSize +
                ", authPasswd='" + authPasswd + '\'' +
                '}';
    }
}