All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.wicp.tams.common.spring.ConfigInit Maven / Gradle / Ivy

There is a newer version: 3.6.1
Show newest version
package net.wicp.tams.common.spring;

import java.util.Map;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.context.support.WebApplicationObjectSupport;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import com.codahale.metrics.Gauge;
import com.codahale.metrics.Metric;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.connector.executor.IBusiManager;
import net.wicp.tams.common.connector.executor.IConfigManager;
import net.wicp.tams.common.connector.executor.busi.KeyConfigManager;
import net.wicp.tams.common.connector.executor.impl.CommonService;
import net.wicp.tams.common.jdbc.DruidAssit;
import net.wicp.tams.common.metrics.core.TsMetricAbstractGroup;
import net.wicp.tams.common.metrics.utility.TsLogger;
import net.wicp.tams.common.redis.RedisAssit;
import net.wicp.tams.common.redis.pool.AbsPool;
import net.wicp.tams.common.spring.connector.ConnectorServlet;
import net.wicp.tams.common.spring.connector.SpringBusiManager;
import net.wicp.tams.common.spring.quartz.IScheduleJobStore;

@Slf4j
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ConfigInit {
	// 为了非spring程序调用spring程序
	public static ApplicationContext context;
	@Autowired
	private SpringAssit springBootAssit;

	@PostConstruct
	private void init() {
		Properties inputpamas = new Properties();
		Properties tpProps = Conf.copyProperties();
		String[] addSingleAry = StringUtil.isNull(Conf.get("common.spring.conf.addSingle")) ? new String[0]
				: Conf.get("common.spring.conf.addSingle").split(",");
		for (String needAddConf : addSingleAry) {
			if (!tpProps.containsKey(needAddConf)) {
				tpProps.put(needAddConf, "null");
			}
		}
		Map allMap = springBootAssit.findAllProps();
		String[] addPreAry = StringUtil.isNull(Conf.get("common.spring.conf.addPre")) ? new String[0]
				: Conf.get("common.spring.conf.addPre").split(",");
		for (String keystr : allMap.keySet()) {
			boolean needAdd = tpProps.containsKey(keystr);
			if (!needAdd) {
				for (String addPreEle : addPreAry) {
					if (StringUtil.isNotNull(addPreEle) && keystr.startsWith(addPreEle)) {
						needAdd = true;
						break;
					}
				}
			}
			if (needAdd) {
				inputpamas.put(keystr, allMap.get(keystr));
			}
		}
		log.info("input parmas:{}", inputpamas.toString());
		Conf.overProp(inputpamas);
	}

	@Configuration
	@Order(Ordered.HIGHEST_PRECEDENCE)
	protected class InitContext implements ApplicationContextAware {
		@Override
		public void setApplicationContext(ApplicationContext arg0) throws BeansException {
			ConfigInit.context = arg0;
		}
	}

	@Configuration
	public class RedisConfig {
		@Bean
		@ConditionalOnMissingBean
		public AbsPool redisPool() {
			AbsPool absPool = RedisAssit.getPool();
			return absPool;
		}
	}

	@Configuration
	@ConditionalOnClass(CommonService.class)
	@Order(Ordered.LOWEST_PRECEDENCE)
	public class ConnectionConfig {
		@Bean
		@ConditionalOnMissingBean
		protected IConfigManager createIConfigManager() {
			IConfigManager manage = new KeyConfigManager();
			return manage;
		}

		@Bean
		protected CommonService createExecutor(ApplicationContext context, IConfigManager configManager,
				AbsPool absPool) {
			CommonService executor = new CommonService();
			IBusiManager busi = new SpringBusiManager(context);
			executor.setBusiManager(busi);
			executor.setConfigManager(configManager);
			executor.setAbsPool(absPool);
			return executor;
		}

		@Bean
		public ConnectorServlet servlet() {
			return new ConnectorServlet();
		}

		// 兼容springboot1 ,不用ServletRegistrationBean
		@Bean
		public ServletRegistrationBean confServlet(ConnectorServlet servlet) {
			ServletRegistrationBean registration = new ServletRegistrationBean(servlet, true, "/connector");
			// registration.setEnabled(true);
			// registration.addUrlMappings("/connector");// connector的默认处理器
			return registration;
		}
	}

	@Configuration
	@ConditionalOnClass(name = "net.wicp.tams.common.jdbc.DruidAssit")
	// @ConditionalOnEnabledEndpoint("env")
	public class DruidDBConfig {
		@Bean("primaryDatasource") // 声明其为Bean实例
		@Primary // 在同样的DataSource中,首先使用被标注的DataSource
		@ConditionalOnClass(name = "net.wicp.tams.common.jdbc.DruidAssit")
		public DataSource dataSource() {
			DataSource datasource = DruidAssit.getInst().getDataSource();
			return datasource;
		}
	}

	@Configuration
	@ConditionalOnClass(name = "org.springframework.web.socket.server.standard.ServerEndpointExporter")
	public class WebSocketConfig {
		@Bean
		@ConditionalOnClass(name = "org.springframework.web.socket.server.standard.ServerEndpointExporter")
		public Object serverEndpointExporter() {
			try {
				Object newInstance = Class
						.forName("org.springframework.web.socket.server.standard.ServerEndpointExporter").newInstance();
				return newInstance;
			} catch (Exception e) {
				throw new RuntimeException("创建ServerEndpointExporter失败");
			}
		}
	}

	// mybatis配置
	// @MapperScan(basePackages = "net.wicp.tams.demo.micro.common.dao",
	// sqlSessionTemplateRef = "primarySqlSessionTemplate") 有了它就不用每个接口写 @Mapper
	// 了,但它不能动态配置,放弃
	@Configuration
	@ConditionalOnClass(name = { "net.wicp.tams.common.jdbc.DruidAssit", "org.mybatis.spring.SqlSessionFactoryBean" })
	public class MybatisConfig {
		@Bean(name = "primarySqlSessionFactory")
		@Primary
		@ConditionalOnBean(name = "primaryDatasource")
		public SqlSessionFactory rdsSqlSessionFactory(
				@Qualifier("primaryDatasource") javax.sql.DataSource primaryDataSource) throws Exception {
			final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
			sessionFactory.setDataSource(primaryDataSource);
			if (StringUtil.isNotNull(Conf.get("common.spring.mybatis.mapperLocations"))) {
				sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
						.getResources(Conf.get("common.spring.mybatis.mapperLocations")));
			}
			if (StringUtil.isNotNull(Conf.get("common.spring.mybatis.configLocation"))) {
				sessionFactory.setConfigLocation(new PathMatchingResourcePatternResolver()
						.getResource(Conf.get("common.spring.mybatis.configLocation")));
			}
			return sessionFactory.getObject();
		}

		@Bean(name = "primarySqlSessionTemplate")
		@Primary
		@ConditionalOnBean(name = "primarySqlSessionFactory")
		public SqlSessionTemplate testSqlSessionTemplate(
				@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
			return new SqlSessionTemplate(sqlSessionFactory);
		}

		@Primary
		@Bean(name = "primaryJdbcTemplate")
		@ConditionalOnBean(name = "primaryDatasource")
		public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDatasource") DataSource dataSource) {
			return new JdbcTemplate(dataSource);
		}
	}

	@Bean
	@ConditionalOnBean(value = IScheduleJobStore.class)
	public SchedulerFactoryBean quartzJob() {
		return new SchedulerFactoryBean();
	}

	// 创建组
	@Bean
	public TsMetricAbstractGroup metrics() {
		System.setProperty(TsLogger.ENV_FILE_NAME, Conf.get("common.spring.metrics.env_file_name"));
		System.setProperty(TsLogger.ENV_FILE_ROOT, Conf.get("common.spring.metrics.env_file_root"));
		return new TamsMetricAbstractGroup(Conf.get("common.spring.metrics.serviceName"));
	}

	private class TamsMetricAbstractGroup extends TsMetricAbstractGroup {
		@SuppressWarnings("unchecked")
		@Override
		public  Gauge newGauge(Gauge gauge, Class tClass, String metricUniqMark) {
			Gauge newGauge = null;
			try {
				newGauge = super.newGauge(gauge, tClass, metricUniqMark);
			} catch (Throwable e) {
				String name = metricName(tClass, metricUniqMark);
				final Metric metric = super.getMetrics().getMetrics().get(name);
				newGauge = (Gauge) metric;
			}
			return newGauge;
		}

		public TamsMetricAbstractGroup(String serviceName) {
			super(serviceName);
		}
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy