系统中不可避免地用到一些常量,如果硬编码,不利于系统运维,一旦需要需要调整,则必须重新编译发布,降低系统的灵活性。
对于这些常量参数,我们通常是放到配置文件中,在系统启动时加载到内存中,如需要调整,修改下配置文件,重启应用系统即可,程序本身不需要编译发布。
客户端我们定义了这样一个全局的配置类,用来实现读取配置参数后进行缓存的目的。
/**
* 客户端配置参数
* 使用spring单例模式
* @author wqliu
* @date 2021-10-5 14:10
*/
@Data
@ConfigurationProperties(prefix = "params")
public class MessageClientConfig
{
/**
* 应用编码
*/
private String appCode;
/**
* 应用密钥
*/
private String appSecret;
/**
* 消息中心主机
*/
private String host;
/**
* 消息中心端口
*/
private int port=8997;
/**
* 心跳频率,单位秒
*/
private int heartbeatRate=5;
/**
* 最大发送次数
*/
private int maxSendCount =4;
/**
* 定时发送消息间隔时间,单位秒
*/
private int sendMessageSpan=30;
/**
* 每次定时发送消息的数量
*/
private int sendMessageCount=10;
/**
* 是否启用消息重发
*/
private boolean enableResend;
/**
* web socket的路径
*/
private String webSocketPath;
/**
* 触发读空闲事件的时间,单位秒
*/
private int readIdleTimeOut;
/**
* 获取web socket的url地址
*/
public String getWebSocketUrl() {
String url= MessageFormat.format("ws://{0}:{1}/{2}",this.getHost(),String.valueOf(this.getPort()),
this.getWebSocketPath());
return url;
}
}
与之对应的,是在yml中配置属性值
params:
appCode: SCS
appSecret: 8543692d-7ea7-4797-a746-47891bff2bec
host: localhost
port: 8997
heartbeatRate: 5
maxSendCount: 4
sendMessageSpan: 30
sendMessageCount: 10
enableResend: true
webSocketPath: webSocket
readIdleTimeOut: 30