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

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