GatewayResourceLoaderConfiguration.java 2.54 KB
package com.diligrp.xtrade.gateway.config;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.diligrp.xtrade.gateway.exception.GatewayServiceException;
import com.diligrp.xtrade.gateway.route.DynamicRouteLoaderIntf;
import com.diligrp.xtrade.gateway.route.impl.CloudRouteResourceLoader;
import com.diligrp.xtrade.gateway.route.impl.MysqlRouteResourceLoader;
import org.apache.logging.log4j.util.Strings;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Properties;

/**
 * @Auther: miaoguoxin
 * @Date: 2020/4/10 13:20
 * @Description: 路由资源加载器配置
 */
@Configuration(proxyBeanMethods = false)
public class GatewayResourceLoaderConfiguration {

    @Bean
    public ConfigService configService(Environment environment,NacosConfigProperties configProperties){
        String username = environment.getProperty("spring.cloud.nacos.config.username");
        String password = environment.getProperty("spring.cloud.nacos.config.password");
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.NAMESPACE, configProperties.getNamespace());
        if (Strings.isNotBlank(username)) {
            properties.put(PropertyKeyConst.USERNAME, username);
            properties.put(PropertyKeyConst.PASSWORD, password);
        }
        properties.put(PropertyKeyConst.SERVER_ADDR, configProperties.getServerAddr());
        ConfigService configService;
        try {
            configService = NacosFactory.createConfigService(properties);
        } catch (NacosException e) {
            throw new GatewayServiceException("init nacos configService failed", e);
        }
        return configService;
    }

    @Bean(name = "cloudRouteResourceLoader")
    @ConditionalOnProperty(prefix = "xtrade",name = "gateway-loader",havingValue = "cloud",matchIfMissing = true)
    public DynamicRouteLoaderIntf cloudRouteResourceLoader(){
        return new CloudRouteResourceLoader();
    }


    @Bean(name = "mysqlRouteResourceLoader")
    @ConditionalOnProperty(prefix = "xtrade",name = "gateway-loader",havingValue = "mysql")
    public DynamicRouteLoaderIntf mysqlRouteResourceLoader(){
        return new MysqlRouteResourceLoader();
    }

}