Java Code Examples for com.jeesuite.common.util.ResourceUtils

The following examples show how to use com.jeesuite.common.util.ResourceUtils. These examples are extracted from open source projects. 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 Project: oneplatform   Source File: Swagger2.java    License: 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 2
Source Project: jeesuite-config   Source File: ServerEnvUtils.java    License: 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 3
Source Project: jeesuite-libs   Source File: ConsumerContext.java    License: 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 4
Source Project: jeesuite-libs   Source File: MutiRouteDataSource.java    License: 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 Project: jeesuite-libs   Source File: MutiRouteDataSource.java    License: 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 6
Source Project: jeesuite-libs   Source File: MybatisConfigs.java    License: 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 7
Source Project: oneplatform   Source File: FileController.java    License: 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 8
Source Project: oneplatform   Source File: ScheduleAdminController.java    License: 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 9
Source Project: oneplatform   Source File: EurekaRegistry.java    License: 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 10
@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 11
Source Project: jeesuite-config   Source File: ServerEnvUtils.java    License: 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 12
Source Project: jeesuite-libs   Source File: TopicConsumerSpringProvider.java    License: 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 13
Source Project: jeesuite-libs   Source File: NewApiTopicConsumer.java    License: 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 Project: jeesuite-libs   Source File: SnowflakeGenerator.java    License: 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 15
Source Project: jeesuite-libs   Source File: SqlSessionFactoryBean.java    License: 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 16
Source Project: jeesuite-libs   Source File: DruidDataSourceBuilder.java    License: 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 17
Source Project: jeesuite-libs   Source File: KafkaProducerProperties.java    License: 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 18
Source Project: jeesuite-libs   Source File: KafkaConsumerProperties.java    License: 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 19
Source Project: oneplatform   Source File: KafkaAdminController.java    License: 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 20
@Override
public String contextPath() {
	return ResourceUtils.getProperty("server.servlet.context-path", "");
}
 
Example 21
Source Project: oneplatform   Source File: RequestLimitFilter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean shouldFilter() {
	return ResourceUtils.getBoolean(REQUEST_LIMIT_ENABLED_KEY);
}
 
Example 22
Source Project: jeesuite-config   Source File: ConfigApplication.java    License: Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
	new SpringApplicationBuilder(ConfigApplication.class).web(WebApplicationType.SERVLET).run(args);
	System.out.println("================================");
	System.out.println("start ok!! env.type:" + ResourceUtils.getProperty("env.type"));
	System.out.println("================================");
}
 
Example 23
Source Project: jeesuite-libs   Source File: TopicProducerSpringProvider.java    License: 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 24
Source Project: jeesuite-libs   Source File: TopicConsumerSpringProvider.java    License: Apache License 2.0 4 votes vote down vote up
@Override
  public void afterPropertiesSet() throws Exception {

if(StringUtils.isNotBlank(scanPackages)){
	String[] packages = org.springframework.util.StringUtils.tokenizeToStringArray(this.scanPackages, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
	scanAndRegisterAnnotationTopics(packages);
}

Validate.isTrue(topicHandlers != null && topicHandlers.size() > 0, "at latest one topic");
//当前状态
if(status.get() > 0)return;

routeEnv = StringUtils.trimToNull(ResourceUtils.getProperty(KafkaConst.PROP_ENV_ROUTE));

if(routeEnv != null){
	logger.info("current route Env value is:",routeEnv);
	Map<String, MessageHandler> newTopicHandlers = new HashMap<>();
	for (String origTopicName : topicHandlers.keySet()) {
		newTopicHandlers.put(routeEnv + "." + origTopicName, topicHandlers.get(origTopicName));
	}
	topicHandlers = newTopicHandlers;
}

//make sure that rebalance.max.retries * rebalance.backoff.ms > zookeeper.session.timeout.ms.
configs.put("rebalance.max.retries", "5");  
configs.put("rebalance.backoff.ms", "1205"); 
configs.put("zookeeper.session.timeout.ms", "6000"); 

configs.put("key.deserializer",StringDeserializer.class.getName());  

if(!configs.containsKey("value.deserializer")){
      	configs.put("value.deserializer", KyroMessageDeserializer.class.getName());
      }

if(useNewAPI){
	if("smallest".equals(configs.getProperty("auto.offset.reset"))){
		configs.put("auto.offset.reset", "earliest");
	}else if("largest".equals(configs.getProperty("auto.offset.reset"))){
		configs.put("auto.offset.reset", "latest");
	}
}else{			
	//强制自动提交
	configs.put("enable.auto.commit", "true");
}

//同步节点信息
groupId = configs.get(org.apache.kafka.clients.consumer.ConsumerConfig.GROUP_ID_CONFIG).toString();

logger.info("\n===============KAFKA Consumer group[{}] begin start=================\n",groupId);

consumerId = NodeNameHolder.getNodeId();
//
configs.put("consumer.id", consumerId);

//kafka 内部处理 consumerId = groupId + "_" + consumerId
consumerId = groupId + "_" + consumerId;
//
if(!configs.containsKey("client.id")){
	configs.put("client.id", consumerId);
}
//
  	start();
  	
  	logger.info("\n===============KAFKA Consumer group[{}],consumerId[{}] start finished!!=================\n",groupId,consumerId);
  }
 
Example 25
Source Project: jeesuite-libs   Source File: Level1CacheSupport.java    License: Apache License 2.0 4 votes vote down vote up
public void setPassword(String password) {
	if(ResourceUtils.NULL_VALUE_PLACEHOLDER.equals(password))return;
	this.password = password;
}
 
Example 26
Source Project: jeesuite-libs   Source File: JedisProviderFactoryBean.java    License: Apache License 2.0 4 votes vote down vote up
public void setPassword(String password) {
	if(ResourceUtils.NULL_VALUE_PLACEHOLDER.equals(password))return;
	this.password = password;
}
 
Example 27
Source Project: jeesuite-libs   Source File: SnowflakeGenerator.java    License: Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
	ResourceUtils.add("spring.application.name", "demo");
	ResourceUtils.add("zookeeper.servers", "127.0.0.1:2181");
	SnowflakeGenerator generator = new SnowflakeGenerator();
	System.out.println(generator.nextId());
}
 
Example 28
Source Project: jeesuite-libs   Source File: SecurityDecisionProvider.java    License: 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;
}
 
Example 29
Source Project: jeesuite-libs   Source File: ZkJobRegistry.java    License: 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 Project: jeesuite-libs   Source File: JobContext.java    License: 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;
}