springboot 使用yml配置文件给静态变量赋值教程-kb88凯时官网登录

时间:2020-05-05
阅读:
免费资源网,https://freexyz.cn/

声明:

此处需求是修改封装的clickhouseutil数据查询引擎连接工具类。由于此类中的方法都是静态方法。连接地址等参数需要根据不同环境改变。例如开发下地址,测试下地址,生产地址等,所有通过配置文件来获取不同环境下的配置参数,但是使用的方法是静态的,所有不能使用一般情况下的@value直接给变量赋值,需要用到spring 属性的set方法来给静态变量赋值,然后静态方法使用静态变量即可

方法:

第一步:在yml文件中配置需要的参数

clickhouse:
 address: jdbc:clickhouse://172.20.xxx.xxx:8123
 username: default
 password: xxxxx
 db: marketing
 sockettimeout: 600000

第二步:

类上一定要先注明@component注解,在程序启动是自动加载,否则静态参数仍旧获取不到配置文件的值

创建静态变量

给静态变量set方法上添加@value()

 @value("${clickhouse.address}")
 public void setclickhouseaddress(string address) {
 clickhouseutil.clickhouseaddress = address;
 }

最后在静态方法中使用即可

@component
public class clickhouseutil {
 
 private static string clickhouseaddress;
 
 private static string clickhouseusername;
 
 private static string clickhousepassword;
 
 private static string clickhousedb;
 
 private static integer clickhousesockettimeout;
 
 @value("${clickhouse.address}")
 public void setclickhouseaddress(string address) {
 clickhouseutil.clickhouseaddress = address;
 }
 @value("${clickhouse.username}")
 public void setclickhouseusername(string username) {
 clickhouseutil.clickhouseusername = username;
 }
 @value("${clickhouse.password}")
 public void setclickhousepassword(string password) {
 clickhouseutil.clickhousepassword = password;
 }
 @value("${clickhouse.db}")
 public void setclickhousedb(string db) {
 clickhouseutil.clickhousedb = db;
 }
 @value("${clickhouse.sockettimeout}")
 public void setclickhousesockettimeout(integer sockettimeout) {
 clickhouseutil.clickhousesockettimeout = sockettimeout;
 }
 
 
 public static connection getconn() {
 
 clickhouseconnection conn = null;
 clickhouseproperties properties = new clickhouseproperties();
 properties.setuser(clickhouseusername);
 properties.setpassword(clickhousepassword);
 properties.setdatabase(clickhousedb);
 properties.setsockettimeout(clickhousesockettimeout);
 clickhousedatasource clickhousedatasource = new clickhousedatasource(clickhouseaddress,properties);
 try {
  conn = clickhousedatasource.getconnection();
  return conn;
 } catch (sqlexception e) {
  e.printstacktrace();
 }
 
 return null;
 }
 
 public static list exesql(string sql){
 log.info("cliockhouse 执行sql:"   sql);
 connection connection = getconn();
 try {
  statement statement = connection.createstatement();
  resultset results = statement.executequery(sql);
  resultsetmetadata rsmd = results.getmetadata();
  list list = new arraylist();
  while(results.next()){
  jsonobject row = new jsonobject();
  for(int i = 1;i<=rsmd.getcolumncount();i  ){
   row.put(rsmd.getcolumnname(i),results.getstring(rsmd.getcolumnname(i)));
  }
  list.add(row);
  }
 
  return list;
 } catch (sqlexception e) {
  e.printstacktrace();
 }
 return null;
 }
 
}
免费资源网,https://freexyz.cn/
返回顶部
顶部
网站地图