美文网首页java
Spring boot 中主动读取Application.yml

Spring boot 中主动读取Application.yml

作者: Zach_6910 | 来源:发表于2020-03-03 18:11 被阅读0次

    原因: 因为配置中心需要统一配置文件原因,未方便后续统一配置变更,现在将redis.properties 中配置迁移到Application.yml 配置中

    原来配置:

    原来读取配置代码:

    // 构建缓存客户端

    private static JedisCluster cluster;

    private static final GsonBuilderbuilder = new GsonBuilder();

    static {

    initialShardedPool();

    }

    private static voidinitialShardedPool() {

    int DEFAULT_TIMEOUT = 2000;////连接超时

    int DEFAULT_REDIRECTIONS = 5;//重试次数

    JedisPoolConfig DEFAULT_CONFIG = new JedisPoolConfig();

    Set hosts = newHashSet();

    // 设置缓存服务器地址,可以设置多个实现分布式缓存

    String cachedPath =PropertiesUtil.getProperty("redis.properties","redis.cluster.nodes").trim();

    String[] servers = cachedPath.split(",");

    if (servers.length > 0) {

    for (int i = 0; i < servers.length; i++) {

    String[] path = servers[i].split(":");

    HostAndPort hp = new HostAndPort(path[0],Integer.parseInt(path[1]));

    hosts.add(hp);

    }

    }

    DEFAULT_CONFIG.setMaxTotal(Integer.parseInt(PropertiesUtil.getProperty("redis.properties","jedis.pool.maxTotal")));

    DEFAULT_CONFIG.setMaxIdle(Integer.parseInt(PropertiesUtil.getProperty("redis.properties","jedis.pool.maxIdle")));

    DEFAULT_CONFIG.setMinIdle(Integer.parseInt(PropertiesUtil.getProperty("redis.properties","jedis.pool.minIdle")));

    DEFAULT_CONFIG.setMaxWaitMillis(Integer.parseInt(PropertiesUtil.getProperty("redis.properties","jedis.pool.maxWaitMillis")));

    String dpass =PropertiesUtil.getProperty("redis.properties","redis.key").trim();

    try {

    //                        

    cluster = new JedisCluster(hosts, DEFAULT_TIMEOUT, //连接超时

    //                                        

            DEFAULT_TIMEOUT,//读写超时

    //                        DEFAULT_REDIRECTIONS, DEFAULT_CONFIG);

     cluster = newJedisCluster(hosts, DEFAULT_TIMEOUT, //连接超时

     DEFAULT_TIMEOUT,//读写超时

     DEFAULT_REDIRECTIONS, dpass,DEFAULT_CONFIG);

    //                        cluster= new JedisCluster(hosts);

    } catch (Exception e) {

    e.printStackTrace();

    }

    }

    修改后Application.yml增加jedis 属性数据:

    创建javabean,来专门映射配置的话,我们一般会使用@ConfigurationProperties来读取.

    packagecom.sitech.pgcent.util;

    importorg.springframework.boot.context.properties.ConfigurationProperties;

    importorg.springframework.stereotype.Component;

    /**

    *@Projectpgcent-project

    *@Packagecom.sitech.pgcent.util

    *@ClassNameJedisApplicationUntil

    *@DescripitionTODO

    *@Authorliuzk

    *@Date2020/3/310:36

    *@Version1.0

    **/

    @Component

    //接收application.yml中的wechat下面的属性

    @ConfigurationProperties(prefix="jedis")

    publicclassJedisApplicationUntil{

    privateStringmaxTotal;

    privateStringmaxIdle;

    privateStringminIdle;

    privateStringmaxWaitMillis;

    privateStringkey;

    privateStringnodes;

    publicStringgetMaxTotal(){

    returnmaxTotal;

    }

    publicvoidsetMaxTotal(StringmaxTotal){

    this.maxTotal=maxTotal;

    }

    publicStringgetMaxIdle(){

    returnmaxIdle;

    }

    publicvoidsetMaxIdle(StringmaxIdle){

    this.maxIdle=maxIdle;

    }

    publicStringgetMinIdle(){

    returnminIdle;

    }

    publicvoidsetMinIdle(StringminIdle){

    this.minIdle=minIdle;

    }

    publicStringgetMaxWaitMillis(){

    returnmaxWaitMillis;

    }

    publicvoidsetMaxWaitMillis(StringmaxWaitMillis){

    this.maxWaitMillis=maxWaitMillis;

    }

    publicStringgetKey(){

    returnkey;

    }

    publicvoidsetKey(Stringkey){

    this.key=key;

    }

    publicStringgetNodes(){

    returnnodes;

    }

    publicvoidsetNodes(Stringnodes){

    this.nodes=nodes;

    }

    }

    当static 语句块中调用initialShardedPool() 方法报错:

    提示信息是


    查看发现报错的原因是在执行静态语句块的时候,@Autowired 还未执行,

    Java变量的初始化顺序为:静态变量或静态语句块–>实例变量或初始化语句块–>构造方法–>@Autowired

    所有会报空指针异常。

    因为必须使用静态语句块读取配置,所有,只能放弃使用spring boot 容器的注解,改成主动读取配置文件。

    1.添加依赖

    2.代码修改

    static{

    initialShardedPool();

    }

    privatestaticvoidinitialShardedPool(){

    intDEFAULT_TIMEOUT=200000;

    intDEFAULT_REDIRECTIONS=5;

    JedisPoolConfigDEFAULT_CONFIG=newJedisPoolConfig();

    Set<HostAndPort>hosts=newHashSet<HostAndPort>();

    //设置缓存服务器地址,可以设置多个实现分布式缓存

    try{

    Yamlyaml=newYaml();

    URLurl=CacheUtil.class.getClassLoader().getResource("application.yml");

    if(url!=null){

    Mapmap=yaml.load(newFileInputStream(url.getFile()));

    MapjedisMap=(Map)map.get("jedis");

    StringcachedPath=(String)jedisMap.get("nodes");

    String[]servers=cachedPath.split(",");

    if(servers.length>0){

    for(inti=0;i<servers.length;i++){

    String[]path=servers[i].split(":");

    HostAndPorthp=newHostAndPort(path[0],Integer.parseInt(path[1]));

    hosts.add(hp);

    }

    }

    DEFAULT_CONFIG

    .setMaxTotal(Integer.parseInt(String.valueOf(jedisMap.get("maxTotal"))));

    DEFAULT_CONFIG

    .setMaxIdle(Integer.parseInt(String.valueOf(jedisMap.get("maxIdle"))));

    DEFAULT_CONFIG

    .setMinIdle(Integer.parseInt(String.valueOf(jedisMap.get("minIdle"))));

    DEFAULT_CONFIG.setMaxWaitMillis(

    Integer.parseInt(String.valueOf(jedisMap.get("maxWaitMillis"))));

    Stringdpass=(String)jedisMap.get("key");

    cluster=newJedisCluster(hosts,DEFAULT_TIMEOUT,DEFAULT_TIMEOUT,

    DEFAULT_REDIRECTIONS,dpass,DEFAULT_CONFIG);

    //cluster=newJedisCluster(hosts,DEFAULT_TIMEOUT,DEFAULT_TIMEOUT,

    //DEFAULT_REDIRECTIONS,DEFAULT_CONFIG);

    //cluster=newJedisCluster(hosts);

    }

    }catch(Exceptione){

    e.printStackTrace();

    }

    }

    3.测试成功

    相关文章

      网友评论

        本文标题:Spring boot 中主动读取Application.yml

        本文链接:https://www.haomeiwen.com/subject/blhklhtx.html