springboot 手动加载redis 配置文件

场景:

如题,springboot 手动加载 配置文件中的加载文件, 本项目的redis 模块是从另一项目中加载过来的,而另一项目使用的

<!--工具类-->
		<dependency>
			<groupId>com.xiaoleilu</groupId>
			<artifactId>hutool-all</artifactId>
			<version>3.3.0</version>
		</dependency>
com.xiaoleilu.hutool.db.nosql.redis.RedisDS 加载的, 但是本项目是一个中小型项目,不想引入太多工具类型的jar包,所有本地采用自己编写的方法解析

redis 配置

redis 配置在 配置文件中 application-x.yml中

spring:
  redis:
    host: localhost
    port: 6379
    password: cloud     # 密码
    timeout: 6000    # 连接超时时长(毫秒)

    jedis.pool:
      #jedis最大分配对象
      maxTotal: 1024
      #jedis最大保存idel状态对象数
      maxIdle: 200
      #jedis池没有对象返回时,最大等待时间
      maxWaitMillis: 10000
      testOnBorrow: true
      testOnReturn: true
      blockWhenExhausted: false
      #Idle时进行连接扫描
      testWhileIdle: true
      #表示idle object evitor两次扫描之间要sleep的毫秒数
      timeBetweenEvictionRunsMillis: 30000
      #表示idle object evitor每次扫描的最多的对象数
      numTestsPerEvictionRun: 10
      #表示一个对象至少停留在idle状态的最短时间,然后才能被idle object evitor扫描并驱逐;这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义
      minEvictableIdleTimeMillis: 60000

读取redis 配置类



import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.env.PropertySourcesLoader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.util.LinkedHashMap;

/**
 * 
 *
 * 读取 redis 配置,或者可以添加其他bean 注入
 *
 */
@Configuration
public class Config {

    Logger logger = Logger.getLogger(this.getClass());

    /**
     * 确定激活的是哪个配置文件
     */
    @Value("${spring.profiles.active}")
    private String active;


    /**
     * @ConditionalOnMissingBean
     * 找不到声明类的情况下创建
     * @return
     */
    @ConditionalOnMissingBean
    @Bean
    public JedisPool jedisPool (JedisPoolConfig config,PropertySource<LinkedHashMap<String,Object>> source) {
        if(null != source) {
            LinkedHashMap<String, Object> sourceMap = source.getSource();

            JedisPool pool = new JedisPool(config, (String) sourceMap.get("spring.redis.host"),(Integer) sourceMap.get("spring.redis.port"),
                    (Integer) sourceMap.get("spring.redis.timeout"),(String) sourceMap.get("spring.redis.password"));
            return pool;
        }
        // 输出创建失败,为了使程序正常启动返回空对象
        logger.error("根据配置创建 JedisPool 失败,创建默认配置的 JedisPool");
        // 使用默认地址 localhost 和默认端口 6379
        return new JedisPool();
    }



    @Bean
    public JedisPoolConfig jedisConfig(PropertySource<LinkedHashMap<String,Object>> source){
        if(null != source ) {
            LinkedHashMap<String,Object> sourceMap = source.getSource();

            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxIdle((Integer) sourceMap.get("spring.redis.jedis.pool.maxIdle"));
            config.setMaxTotal((Integer)sourceMap.get("spring.redis.jedis.pool.maxTotal"));
            config.setMaxWaitMillis(Long.valueOf(sourceMap.get("spring.redis.jedis.pool.maxWaitMillis").toString()));
            config.setTestOnBorrow((Boolean)sourceMap.get("spring.redis.jedis.pool.testOnBorrow"));
            config.setTestOnReturn((Boolean)sourceMap.get("spring.redis.jedis.pool.testOnReturn"));
            config.setBlockWhenExhausted((Boolean)sourceMap.get("spring.redis.jedis.pool.blockWhenExhausted"));
            config.setTestWhileIdle((Boolean)sourceMap.get("spring.redis.jedis.pool.testWhileIdle"));
            config.setTimeBetweenEvictionRunsMillis(Long.valueOf(sourceMap.get("spring.redis.jedis.pool.timeBetweenEvictionRunsMillis").toString()));
            config.setNumTestsPerEvictionRun((Integer)sourceMap.get("spring.redis.jedis.pool.timeBetweenEvictionRunsMillis"));
            config.setMinEvictableIdleTimeMillis(Long.valueOf(sourceMap.get("spring.redis.jedis.pool.minEvictableIdleTimeMillis").toString()));
            return config;
        }
        // 输出创建失败
        logger.error("创建 JedisPoolConfig 失败");
        return new JedisPoolConfig();

    }


    /**
     * 读取配置文件
     */
    @Bean
    public PropertySource<LinkedHashMap<String,Object>> readProperties(){
        String yml = "application-" + active +".yml";
        ClassPathResource resource = new ClassPathResource(yml);
        PropertySourcesLoader loader = new PropertySourcesLoader();
        PropertySource<LinkedHashMap<String,Object>> load;
        try {
            load = (PropertySource<LinkedHashMap<String,Object>>) loader.load(resource);
            return load;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }




}

得到了JedisPool

就可以通过 JedisPool 得到具体的连接,从来进行各种操作

@Component("RedisService")
public class RedisService {

  

    /**
     * 单机版
     */
    @Autowired
    private static JedisPool jedisPool;

    /**
     * JedisPool 单机版
     */
    @Autowired
    public  void setJedisPool(JedisPool jedisPool) {
        RedisService.jedisPool = jedisPool;
    }

   

// ... 各种操作redis 的方法

}

后续:

其实没想那么多,就是觉得 既然 这个 redisService 类 需要一个 jedisPool ,就给他 通过 @Bean的方式new 一个出来,然后找了半天 springboot 读取 .yml 文件的工具类,后来发现一个 springboot 有自带的工具类

YamlPropertySourceLoader 但是发现文档注释不全,不知道什么意思,调用不成功,后来又发现有公共的读取工具类 
PropertySourcesLoader ,这样才读取成功,后续类型转换 和 取值 还是比较

后来又发现springboot 有自带的 redis 读取配置类, RedisProperties

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章