com.jeesuite.common.util.ResourceUtils Java Examples

The following examples show how to use com.jeesuite.common.util.ResourceUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MybatisConfigs.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
public static String[] getHanlderNames(String group){
       List<String> hanlders = new ArrayList<>();
	if(ResourceUtils.containsProperty(INTERCEPTOR_HANDLERCLASS)){
		String[] customHanlderClass = StringUtils.tokenizeToStringArray(ResourceUtils.getProperty(INTERCEPTOR_HANDLERCLASS), ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
		hanlders.addAll(Arrays.asList(customHanlderClass));
	}
	
	if (isCacheEnabled(group)) {
		hanlders.add(CacheHandler.NAME);
	}

	if (isRwRouteEnabled(group)) {
		hanlders.add(RwRouteHandler.NAME);
	}
	
	if (isPaginationEnabled(group)) {
		hanlders.add(PaginationHandler.NAME);
	}
	
	return hanlders.toArray(new String[0]);
}
 
Example #2
Source File: Swagger2.java    From oneplatform with Apache License 2.0 6 votes vote down vote up
@Bean
public Docket createRestApi(@Value("${swagger.enable:false}") boolean enable) {
	String basePackage = ResourceUtils.getProperty("controller.base-package","com.oneplatform");
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .enable(enable)
            .groupName("oneplatform")  
            .genericModelSubstitutes(DeferredResult.class)  
            .useDefaultResponseMessages(false)  
            //.globalResponseMessage(RequestMethod.GET,customerResponseMessage())  
            .forCodeGeneration(true)  
            .select()
            .apis(RequestHandlerSelectors.basePackage(basePackage))
            .paths(PathSelectors.any())
            .build();
}
 
Example #3
Source File: MutiRouteDataSource.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
/** 
   * 功能说明:解析配置,得到数据源Map 
   * @return 
   * @throws IOException 
   */  
  private Map<String, Properties> parseDataSourceConfig(){  
      // 属性文件  
      Map<String, Properties> mapDataSource = new HashMap<String,Properties>(); 
      
String datasourceKey = MASTER_KEY;
Properties nodeProperties = parseNodeConfig(datasourceKey); 
mapDataSource.put(datasourceKey, nodeProperties);

//解析同组下面的slave
int index = 1;
while(true){
	datasourceKey = "slave" + index;
	if(!ResourceUtils.containsProperty(datasourceKey + ".db.url") && !ResourceUtils.containsProperty(datasourceKey + ".db.jdbcUrl"))break;
	nodeProperties = parseNodeConfig(datasourceKey); 
	mapDataSource.put(datasourceKey, nodeProperties);
	index++;
}

      return mapDataSource;  
  }
 
Example #4
Source File: MutiRouteDataSource.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
	
	try {	
		dataSourceType = DataSourceType.valueOf(ResourceUtils.getProperty("db.DataSourceType", DataSourceType.Druid.name()));
	} catch (Exception e) {
		throw new IllegalArgumentException("Property 'db.DataSourceType' expect:" + Arrays.toString(DataSourceType.values()));
	}
			
	Map<String, Properties> map = parseDataSourceConfig();
	
	if(map.isEmpty())throw new RuntimeException("Db config Not found..");
	registerDataSources(map);
	
	if (this.targetDataSources == null || targetDataSources.isEmpty()) {
		throw new IllegalArgumentException("Property 'targetDataSources' is required");
	}
	
	if (this.defaultDataSource == null) {
		throw new IllegalArgumentException("Property 'defaultDataSource' is required");
	}
}
 
Example #5
Source File: ServerEnvUtils.java    From jeesuite-config with Apache License 2.0 6 votes vote down vote up
public static String getServerIpAddr()  {  
	if(ResourceUtils.containsProperty("spring.cloud.client.ipAddress")){
		return ResourceUtils.getProperty("spring.cloud.client.ipAddress");
	}
	if(serverIpAddr != null)return serverIpAddr;
	try {
		Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();  
		outter:while (en.hasMoreElements()) {  
			NetworkInterface i = en.nextElement();  
			for (Enumeration<InetAddress> en2 = i.getInetAddresses(); en2.hasMoreElements();) {  
				InetAddress addr = en2.nextElement();  
				if (!addr.isLoopbackAddress()) {  
					if (addr instanceof Inet4Address) {    
						serverIpAddr = addr.getHostAddress();  
						break outter;
					}  
				}  
			}  
		}  
	} catch (Exception e) {
		serverIpAddr = UNKNOW;
	}
    return serverIpAddr;  
}
 
Example #6
Source File: ConsumerContext.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
public void propertiesSetIfAbsent(Properties configs, String groupId, String consumerId,
		Map<String, MessageHandler> messageHandlers, int maxProcessThreads,
		OffsetLogHanlder offsetLogHanlder,ErrorMessageProcessor errorMessageProcessor) {
	if(this.configs != null)return;
	this.configs = configs;
	this.groupId = groupId;
	this.consumerId = consumerId;
	this.messageHandlers = messageHandlers;
	this.maxProcessThreads = maxProcessThreads;
	this.offsetLogHanlder = offsetLogHanlder;
	this.errorMessageProcessor = errorMessageProcessor;
	
	String zkServers = ResourceUtils.getProperty("kafka.zkServers");
	if(StringUtils.isNotBlank(zkServers)){
       	zkClient = new ZkClient(zkServers, 10000, 5000, new ZKStringSerializer());
	}
}
 
Example #7
Source File: ScheduleAdminController.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	if("zookeeper".equals(ResourceUtils.getProperty("jeesuite.task.registryType")) && 
			ResourceUtils.containsProperty("jeesuite.task.registryServers")){
		monitor = new SchedulerMonitor("zookeeper", ResourceUtils.getProperty("jeesuite.task.registryServers"));
	}else{
		monitor = new SchedulerMonitor(null, null);
	}
}
 
Example #8
Source File: KafkaConsumerProperties.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	String kafkaServers = ResourceUtils.getProperty("kafka.bootstrap.servers");
	String zkServers = ResourceUtils.getProperty("kafka.zkServers");
	configs.put("bootstrap.servers", kafkaServers);
	if(useNewAPI == false && zkServers != null){
		configs.put("zookeeper.connect", zkServers);
	}
	Properties properties = ResourceUtils.getAllProperties("kafka.consumer.");
	Iterator<Entry<Object, Object>> iterator = properties.entrySet().iterator();
	while(iterator.hasNext()){
		Entry<Object, Object> entry = iterator.next();
		configs.put(entry.getKey().toString().replace("kafka.consumer.", ""), entry.getValue());
	}
}
 
Example #9
Source File: KafkaProducerProperties.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	String kafkaServers = ResourceUtils.getProperty("kafka.bootstrap.servers");
	configs.put("bootstrap.servers", kafkaServers);
	Properties properties = ResourceUtils.getAllProperties("kafka.producer.");
	Iterator<Entry<Object, Object>> iterator = properties.entrySet().iterator();
	while(iterator.hasNext()){
		Entry<Object, Object> entry = iterator.next();
		configs.put(entry.getKey().toString().replace("kafka.producer.", ""), entry.getValue());
	}
}
 
Example #10
Source File: DruidDataSourceBuilder.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
public static BeanDefinitionBuilder builder(Properties props){
	
	BeanDefinitionBuilder beanDefinitionBuilder =  BeanDefinitionBuilder.genericBeanDefinition(DruidDataSource.class);
	
	String cryptKey = props.getProperty("config.cryptKey");
	if(props.containsKey("name"))beanDefinitionBuilder.addPropertyValue("name", props.getProperty("name"));
   	beanDefinitionBuilder.addPropertyValue("driverClassName", props.getProperty("driverClassName"));
   	beanDefinitionBuilder.addPropertyValue("url", props.getProperty("url"));
   	beanDefinitionBuilder.addPropertyValue("username", props.getProperty("username"));
   	
   	String password = props.getProperty("password");
   	if(StringUtils.isNotBlank(cryptKey) && !ResourceUtils.NULL_VALUE_PLACEHOLDER.equals(cryptKey)){
   		try {
   			password = SimpleCryptUtils.decrypt(cryptKey, password);
		} catch (Exception e) {
			System.err.println(">> find config[db.config.cryptKey],but decrypt error ,use orign password");
		}
   	}
   	beanDefinitionBuilder.addPropertyValue("password", password);
   	beanDefinitionBuilder.addPropertyValue("testWhileIdle", Boolean.parseBoolean(props.getProperty("testWhileIdle","true")));
   	beanDefinitionBuilder.addPropertyValue("validationQuery", props.getProperty("validationQuery","SELECT 'x'"));
   	beanDefinitionBuilder.addPropertyValue("maxActive", Integer.parseInt(props.getProperty("maxActive","10")));
   	beanDefinitionBuilder.addPropertyValue("initialSize", Integer.parseInt(props.getProperty("initialSize","1")));
   	beanDefinitionBuilder.addPropertyValue("minIdle", Integer.parseInt(props.getProperty("minIdle","1")));
   	beanDefinitionBuilder.addPropertyValue("maxWait", Long.parseLong(props.getProperty("maxWait","10000")));
   	beanDefinitionBuilder.addPropertyValue("minEvictableIdleTimeMillis", Long.parseLong(props.getProperty("minEvictableIdleTimeMillis","60000")));
   	beanDefinitionBuilder.addPropertyValue("timeBetweenEvictionRunsMillis", Long.parseLong(props.getProperty("timeBetweenEvictionRunsMillis","60000")));
   	beanDefinitionBuilder.addPropertyValue("testOnBorrow", Boolean.parseBoolean(props.getProperty("testOnBorrow","true")));
   	beanDefinitionBuilder.addPropertyValue("testOnReturn", Boolean.parseBoolean(props.getProperty("testOnReturn","false")));

   	return beanDefinitionBuilder;
       
}
 
Example #11
Source File: SqlSessionFactoryBean.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	super.afterPropertiesSet();
	MybatisMapperParser.addMapperLocations(groupName, mapperLocations);
	String prefix = "default".equals(groupName) ? "jeesuite.mybatis" : groupName + ".jeesuite.mybatis";
	MybatisConfigs.addProperties(groupName, ResourceUtils.getAllProperties(prefix));
	Configuration configuration = getObject().getConfiguration();
	JeesuiteMybatisRegistry.register(groupName,configuration);
}
 
Example #12
Source File: SnowflakeGenerator.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
/**
 * 需要zookeeper保存节点信息
 */
public SnowflakeGenerator() {
	try {
		String appName = ResourceUtils.getProperty("spring.application.name", ResourceUtils.getProperty("jeesuite.configcenter.appName"));
		Validate.notBlank(appName, "config[spring.application.name] not found");
		String zkServer = ResourceUtils.getAndValidateProperty("zookeeper.servers");
		
		zk = new ZooKeeper(zkServer, 10000, this);
		String path = String.format(ROOT_PATH, appName);
		
		String[] parts = StringUtils.split(path, "/");
		String tmpParent = "";
		Stat stat;
		for (int i = 0; i < parts.length; i++) {
			tmpParent = tmpParent + "/" + parts[i];
			stat = zk.exists(tmpParent, false);
			if (stat == null) {
				zk.create(tmpParent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
			}
		}
		String nodePath = path + "/" + NodeNameHolder.getNodeId();
		zk.create(nodePath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
		int workerId = zk.getChildren(path, false).size();
		if (workerId > maxWorkerId || workerId < 0) {
			throw new IllegalArgumentException(
					String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
		}
		this.workerId = workerId;
	} catch (Exception e) {
		this.workerId = RandomUtils.nextInt(1, 31);
	}
	this.datacenterId = 1;
}
 
Example #13
Source File: NewApiTopicConsumer.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
public NewApiTopicConsumer(ConsumerContext context) {
	super(context);
	properties = context.getProperties();
	clientIdPrefix = properties.getProperty(ConsumerConfig.CLIENT_ID_CONFIG);
	this.topicHandlers = context.getMessageHandlers();
	//enable.auto.commit 默认为true
	offsetAutoCommit = context.getProperties().containsKey("enable.auto.commit") == false || Boolean.parseBoolean(context.getProperties().getProperty("enable.auto.commit"));
    if(properties.containsKey("poll.timeout.ms")){	    	
    	pollTimeout = Long.parseLong(properties.remove("poll.timeout.ms").toString());
    }else{
    	pollTimeout = Long.parseLong(ResourceUtils.getProperty("consumer.poll.timeout.ms", "1000"));
    }
    logger.info("pollTimeout:"+pollTimeout);
}
 
Example #14
Source File: TopicConsumerSpringProvider.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
/**
 * 
 */
@SuppressWarnings("rawtypes")
private void registerKafkaSubscriber() {
	//状态:启动中
	status.set(1);
	
	Validate.notEmpty(this.configs, "configs is required");
	Validate.notEmpty(this.configs.getProperty("group.id"), "kafka configs[group.id] is required");
	Validate.notEmpty(this.configs.getProperty("bootstrap.servers"), "kafka configs[bootstrap.servers] is required");
	
       StringBuffer sb = new StringBuffer();
       Iterator itr = this.configs.entrySet().iterator();
	while (itr.hasNext()) {
		Entry e = (Entry) itr.next();
		sb.append(e.getKey()).append("  =  ").append(e.getValue()).append("\n");
	}
	logger.info("\n============kafka.Consumer.Config============\n" + sb.toString() + "\n");

	ConsumerContext consumerContext = ConsumerContext.getInstance();
	int retryNums = ResourceUtils.getInt("message.consumer.retry.counts", 3);
	consumerContext.propertiesSetIfAbsent(configs, groupId, consumerId, topicHandlers, processThreads,offsetLogHanlder ,new ErrorMessageProcessor(1, 10, retryNums, retryErrorMessageHandler));

	if(useNewAPI){			
		consumer = new NewApiTopicConsumer(consumerContext);
	}else{
		consumer = new OldApiTopicConsumer(consumerContext);
	}
	
       //TODO 确保spring全部加载完成再start
       consumer.start();
       //状态:运行中
       status.set(2);
}
 
Example #15
Source File: FileController.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	Properties properties = ResourceUtils.getAllProperties();
	Set<Entry<Object, Object>> entrySet = properties.entrySet();
	for (Entry<Object, Object> entry : entrySet) {
		if(entry.getKey().toString().endsWith(".filesystem.provider")){
			uploadGroups.add(entry.getKey().toString().split("\\.")[0]);
			if(!uploadProviders.contains(entry.getValue().toString()))uploadProviders.add(entry.getValue().toString());
		}
	}
}
 
Example #16
Source File: ServerEnvUtils.java    From jeesuite-config with Apache License 2.0 5 votes vote down vote up
public static String getServerPort(){
	if(serverPort != null && !UNKNOW.equals(serverPort)){
		return serverPort;
	}
	serverPort = ResourceUtils.getProperty("server.port");
	if(StringUtils.isBlank(serverPort)){
		serverPort = ResourceUtils.getProperty("dubbo.port");
	}
	if(StringUtils.isBlank(serverPort)){
		serverPort = getTomcatServerPortByMBean();
	}
	
	return serverPort;
}
 
Example #17
Source File: EurekaRegistry.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
private void initEurekaClient(Properties properties) throws Exception{
	
	properties.setProperty("eureka.metadataMap.nodeId", NodeNameHolder.getNodeId());
	ConfigurationManager.loadProperties(properties);
	//ConfigurationManager.loadPropertiesFromResources("eureka.properties");
	
	//DynamicPropertyFactory configInstance = com.netflix.config.DynamicPropertyFactory.getInstance();
	
	MyDataCenterInstanceConfig instanceConfig = new MyDataCenterInstanceConfig(){
		@Override
		public String getHostName(boolean refresh) {
			String hostName = super.getHostName(refresh);
			if(ResourceUtils.getBoolean("eureka.preferIpAddress")){
				hostName = IpUtils.getLocalIpAddr();
			}
			return hostName;
		}

		@Override
		public String getIpAddress() {
			return IpUtils.getLocalIpAddr();
		}
		
		
	};
	InstanceInfo instanceInfo = new EurekaConfigBasedInstanceInfoProvider(instanceConfig).get();
       applicationInfoManager = new ApplicationInfoManager(instanceConfig, instanceInfo);
       
       DefaultEurekaClientConfig clientConfig = new DefaultEurekaClientConfig();

       eurekaClient = new DiscoveryClient(applicationInfoManager, clientConfig);
       
       instanceId = instanceInfo.getInstanceId();
}
 
Example #18
Source File: OnePlatformSecurityDecisionProvider.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> anonymousUrlPatterns() {
	List<String> result = permissionService.buildGlobalPermissionCodes().get(PermissionType.Anonymous);
	if(result == null)result = new ArrayList<>();
	result.addAll(Arrays.asList(StringUtils.splitByWholeSeparator(ResourceUtils.getProperty("anonymous.uris"), ";")));
	return result;
}
 
Example #19
Source File: TopicProducerSpringProvider.java    From jeesuite-libs with Apache License 2.0 4 votes vote down vote up
@Override
  public void afterPropertiesSet() throws Exception {

      Validate.notEmpty(this.configs, "configs is required");
      
      routeEnv = StringUtils.trimToNull(ResourceUtils.getProperty(KafkaConst.PROP_ENV_ROUTE));
      
      if(routeEnv != null)log.info("current route Env value is:",routeEnv);
    //移除错误的或者未定义变量的配置
      Set<String> propertyNames = configs.stringPropertyNames();
      for (String propertyName : propertyNames) {
	String value = configs.getProperty(propertyName);
	if(StringUtils.isBlank(value) || value.trim().startsWith("$")){
		configs.remove(propertyName);
		log.warn("remove prop[{}],value is:{}",propertyName,value);
	}
}
      
      if(!configs.containsKey(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG)){
      	configs.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); // key serializer
      }
      
      if(!configs.containsKey(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG)){
      	configs.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KyroMessageSerializer.class.getName());
      }
      
      if(!configs.containsKey(ProducerConfig.PARTITIONER_CLASS_CONFIG)){
      	configs.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, DefaultPartitioner.class.getName()); 
      }
      
      //默认重试一次
      if(!configs.containsKey(ProducerConfig.RETRIES_CONFIG)){
      	configs.put(ProducerConfig.RETRIES_CONFIG, "1"); 
      }
      
      if(!configs.containsKey(ProducerConfig.COMPRESSION_TYPE_CONFIG)){
      	configs.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy"); 
      }
      
      if(!configs.containsKey("client.id")){
	configs.put("client.id", (producerGroup == null ? "" : "_"+producerGroup) + NodeNameHolder.getNodeId());
}

      KafkaProducer<String, Object> kafkaProducer = new KafkaProducer<String, Object>(configs);

      String monitorZkServers = ResourceUtils.getProperty("kafka.zkServers");
      if(StringUtils.isNotBlank(monitorZkServers)){
      	zkClient = new ZkClient(monitorZkServers, 10000, 5000, new ZKStringSerializer());
      }
      this.producer = new DefaultTopicProducer(kafkaProducer,zkClient,consumerAckEnabled);

      //hanlder
      if(monitorEnabled){    
	Validate.notBlank(producerGroup,"enable producer monitor property[producerGroup] is required");
	Validate.notNull(zkClient, "enable producer monitor property[kafka.zkServers] is required");
	
	this.producer.addEventHandler(new SendCounterHandler(producerGroup,zkClient));
}
      if(delayRetries > 0){
      	this.producer.addEventHandler(new SendErrorDelayRetryHandler(producerGroup,kafkaProducer, delayRetries));
      }
  }
 
Example #20
Source File: KafkaAdminController.java    From oneplatform with Apache License 2.0 4 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	if(ResourceUtils.containsProperty("zookeeper.servers") && ResourceUtils.containsProperty("kafka.bootstrap.servers")){
		 monitor = new KafkaMonitor(ResourceUtils.getProperty("zookeeper.servers"), ResourceUtils.getProperty("kafka.bootstrap.servers"), 1000);
	}
}
 
Example #21
Source File: FilterConfig.java    From jeesuite-libs with Apache License 2.0 4 votes vote down vote up
public static boolean apiDocEnabled(){
	return Boolean.parseBoolean(ResourceUtils.getProperty("apidoc.enabled", "true"));
}
 
Example #22
Source File: FilterConfig.java    From jeesuite-libs with Apache License 2.0 4 votes vote down vote up
public static boolean reqRspLogEnabled(){
	return Boolean.parseBoolean(ResourceUtils.getProperty("reqres.log.enabled", "false"));
}
 
Example #23
Source File: FilterConfig.java    From jeesuite-libs with Apache License 2.0 4 votes vote down vote up
public static String getCorsAllowOrgin(){
	return ResourceUtils.getProperty("cors.allow.origin", "*");
}
 
Example #24
Source File: FilterConfig.java    From jeesuite-libs with Apache License 2.0 4 votes vote down vote up
public static boolean corsEnabled(){
	return Boolean.parseBoolean(ResourceUtils.getProperty("cors.enabled", "false"));
}
 
Example #25
Source File: OnePlatformSecurityDecisionProvider.java    From oneplatform with Apache License 2.0 4 votes vote down vote up
@Override
public String contextPath() {
	return ResourceUtils.getProperty("server.servlet.context-path", "");
}
 
Example #26
Source File: RequestLimitFilter.java    From oneplatform with Apache License 2.0 4 votes vote down vote up
@Override
public boolean shouldFilter() {
	return ResourceUtils.getBoolean(REQUEST_LIMIT_ENABLED_KEY);
}
 
Example #27
Source File: LogConfigLookup.java    From jeesuite-libs with Apache License 2.0 4 votes vote down vote up
@Override
public String lookup(LogEvent event, String key) {
	return ResourceUtils.getProperty(key);
}
 
Example #28
Source File: JobContext.java    From jeesuite-libs with Apache License 2.0 4 votes vote down vote up
public void setRegistry(JobRegistry registry) {
	if(ResourceUtils.getBoolean("jeesuite.task.registry.disabled", false)){
       	return;
       }
	this.registry = registry;
}
 
Example #29
Source File: ZkJobRegistry.java    From jeesuite-libs with Apache License 2.0 4 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
       if(ResourceUtils.getBoolean("jeesuite.task.registry.disabled", false)){
       	return;
       }
	ZkConnection zkConnection = new ZkConnection(zkServers);
	zkClient = new ZkClient(zkConnection, 10000);
	//
	zkCheckTask = Executors.newScheduledThreadPool(1);

	zkCheckTask.scheduleAtFixedRate(new Runnable() {
		@Override
		public void run() {
			if (schedulerConfgs.isEmpty())
				return;
			List<String> activeNodes = null;
			try {
				activeNodes = zkClient.getChildren(nodeStateParentPath);
				zkAvailabled = true;
			} catch (Exception e) {
				checkZkAvailabled();
				activeNodes = new ArrayList<>(JobContext.getContext().getActiveNodes());
			}

			if (!activeNodes.contains(JobContext.getContext().getNodeId())) {
				zkClient.createEphemeral(nodeStateParentPath + "/" + JobContext.getContext().getNodeId());
				logger.info("node[{}] re-join task clusters", JobContext.getContext().getNodeId());
			}
			// 对节点列表排序
			Collections.sort(activeNodes);
			// 本地缓存的所有jobs
			Collection<JobConfig> jobConfigs = schedulerConfgs.values();
			//
			for (JobConfig jobConfig : jobConfigs) {
				// 如果本地任务指定的执行节点不在当前实际的节点列表,重新指定
				if (!activeNodes.contains(jobConfig.getCurrentNodeId())) {
					// 指定当前节点为排序后的第一个节点
					String newExecuteNodeId = activeNodes.get(0);
					jobConfig.setCurrentNodeId(newExecuteNodeId);
					logger.warn("Job[{}-{}] currentNodeId[{}] not in activeNodeList, assign new ExecuteNodeId:{}",
							jobConfig.getGroupName(), jobConfig.getJobName(), jobConfig.getCurrentNodeId(),
							newExecuteNodeId);
				}
			}
		}
	}, 60, 30, TimeUnit.SECONDS);
}
 
Example #30
Source File: SecurityDecisionProvider.java    From jeesuite-libs with Apache License 2.0 4 votes vote down vote up
public CacheType cacheType(){
	if(CacheType.redis.name().equals(ResourceUtils.getProperty(SecurityConstants.CONFIG_STORAGE_TYPE))){
		return CacheType.redis;
	}
	return CacheType.local;
}