1 분 소요

redis 연결을 위해 RedisConfig.java를 작성해야 했는데,
이때 porthost 정보를 직접 적는 것이 아니라, 따로 secret.yml에 기입한 뒤에,
해당 파일은 .gitignore를 통해 깃에 올리지 않고 해당 정보만 가져와서 사용하고 싶었다.

아래와 같이 환경변수를 담은 yml 파일이 존재한다. secret.yml

redis:
  host: localhost
  port: 6379
cache:
  type: redis

이 파일은 .gitignore에 등록하여 깃에 올라기지 않도록 한다.

1. YamlPropertySourceFactory.java 작성

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException) {
                throw (FileNotFoundException)e.getCause();
            }
            throw e;
        }
    }
}

application.yml 파일이 아닌, 임의로 생성한 yml 파일을 읽기 위해 필요한 클래스이다.
PropertySourceFactory를 상속받아 구현한다.

2. SecretYamlRead.java 작성

@Configuration
@PropertySource(value = "classpath:secret.yml", factory = YamlPropertySourceFactory.class) //value를 통해 값이 있는 위치를 명시해준다.
@ConfigurationProperties(prefix = "redis") // classpath에 적은 yml 파일에서 가져올 변수 이름을 명시해준다.
@Getter
@Setter
public class SecretYamlRead {

    private String host;
    private String port;

}

secretYamlRead에 필요한 것은 두 가지이다.

  1. secret.yml
  2. YamlPropertySourceFactory

3. RedisConfig.java 작성

@Configuration
public class RedisConfig {

    // ===========================================
    @Autowired
    private SecretYamlRead secretYamlRead;

    String host = secretYamlRead.getHost();
    int port = Integer.parseInt(secretYamlRead.getPort());
    // ===========================================

    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory(host, port);
    }

    @Bean
    public RedisTemplate<?, ?> redisTemplate() {
        RedisTemplate<?, ?> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory());
        return redisTemplate;
    }
}

강조한 부분을 주목하면 된다.
이처럼 secretYamlRead를 통해 hostport 정보를 가져올 수 있다.

Ref.



💛 개인 공부 기록용 블로그입니다. 👻

맨 위로 이동하기

태그:

카테고리:

업데이트: