Compare commits

...

34 Commits

Author SHA1 Message Date
liaochuntao ae79de4b97
Merge pull request #38 from chuntaojun/1.x
1.x
2019-07-25 12:14:14 +08:00
chuntaojun 3cc49b3d8e fix(config): fix NacosConfigAutoConfiguration 2019-07-25 11:45:33 +08:00
chuntaojun 7b78753758 fix(config): remove beanfactory register singleton object 2019-07-25 11:43:12 +08:00
chuntaojun 4e102e56d1 fix: 2019-07-25 11:31:40 +08:00
chuntaojun f94a675959 refactor: update version to 0.1.2 2019-07-25 11:26:39 +08:00
liaochuntao 842b0e2135
Merge pull request #33 from chuntaojun/1.x
support new feature and fix issue #18
2019-07-19 11:45:22 +08:00
chuntaojun c63c09f580 ci: 2019-07-19 11:42:20 +08:00
chuntaojun 9e91534831 ci: 2019-07-19 11:31:19 +08:00
chuntaojun 8baae0e520 ci: 2019-07-19 11:27:34 +08:00
chuntaojun 5b389c1b84 ci: 2019-07-19 11:06:26 +08:00
chuntaojun 4eeb85fc6f ci: 2019-07-19 11:02:48 +08:00
chuntaojun c5bce068fa fix(config): remove unuse package 2019-07-19 10:58:02 +08:00
chuntaojun 8b3f1a37c2 feat: 2019-07-19 10:51:43 +08:00
chuntaojun 844242b493 feat(config): support new nacos-client feature and spring-nacos-project feature 2019-07-19 10:41:12 +08:00
chuntaojun 0a9f54f215 feat: 2019-07-19 09:35:14 +08:00
fangjian0423 21972f263b fix test case for 1.x branch 2019-01-29 16:13:08 +08:00
fangjian0423 483271f2ee remove sk in healthindicator and endpoint 2019-01-16 11:39:27 +08:00
fangjian0423 77a0b1ef6d remove duplicate maven plugin 2018-12-13 20:42:39 +08:00
fangjian0423 5bfc05876a update version for 1.x branch 2018-12-13 20:32:37 +08:00
fangjian0423 050d10ab5a add conditional to NacosConfigAutoConfiguration, NacosDiscoveryAutoConfiguration for springboot 1.x 2018-09-26 21:51:35 +08:00
format c5498e440d
Update README.md 2018-09-26 19:04:51 +08:00
fangjian0423 546dd7df39 Integrate with Travis CI 2018-09-26 17:44:34 +08:00
fangjian0423 6cf028d929 Integrate with Travis CI 2018-09-26 17:41:00 +08:00
fangjian0423 83e0bc6809 update nacos spring version 2018-09-26 17:29:58 +08:00
fangjian0423 d839e5c9a6 Integrate with Travis CI 2018-09-26 17:24:34 +08:00
fangjian0423 1f7bcb2736 add nacos server detail info in health indicator 2018-09-25 15:46:19 +08:00
fangjian0423 e4c4d39f18 update samples 2018-09-25 15:17:33 +08:00
fangjian0423 4ff3b44268 modify conditional class in nacos config, discovery actuator 2018-09-25 15:17:21 +08:00
fangjian0423 8fc2b59dbe fix test case 2018-09-22 14:32:07 +08:00
fangjian0423 b84631340f Update documents 2018-09-20 11:44:08 +08:00
fangjian0423 09833490d2 Update documents 2018-09-20 11:39:55 +08:00
fangjian0423 21f9944b6f modify nacos config sample, update docs, modify endpoints 2018-09-19 16:37:20 +08:00
fangjian0423 ac97b09c18 Update documents 2018-09-18 21:23:27 +08:00
fangjian0423 a28b60f1b3 commit 1.x branch to support springboot 1.x 2018-09-18 17:36:53 +08:00
48 changed files with 609 additions and 614 deletions

View File

@ -6,10 +6,12 @@ notifications:
on_success: change
on_failure: always
dist: trusty
language: java
jdk:
- openjdk10
- openjdk8
- openjdk7
script:

View File

@ -1,144 +0,0 @@
### Nacos Config
First, you have to start a Nacos Server in backend , If you don't know steps, you can learn about [quick start](https://nacos.io/en-us/docs/quick-start.html).
Suppose your Nacos Server is startup, you would add [`nacos-config-spring-boot-starter`](nacos-config-spring-boot-starter) in your Spring application's dependencies :
```xml
<dependencies>
...
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>${latest.version}</version>
</dependency>
...
</dependencies>
```
Note: Version [0.2.x.RELEASE](https://mvnrepository.com/artifact/com.alibaba.boot/nacos-config-spring-boot-starter) is compatible with the Spring Boot 2.x. Version [0.1.x.RELEASE](https://mvnrepository.com/artifact/com.alibaba.boot/nacos-config-spring-boot-starter) is compatible with the Spring Boot 1.x.
After that, you could define some configurations in `application.properties`:
```properties
nacos.config.server-addr=localhost:8848
```
> `nacos.config.server-addr` attribute configures "\${host}:${port}" of your Nacos Server
Then you could using `@SpringBootApplication` to annotate main class like normal SpringBoot Application and startup:
```java
@SpringBootApplication
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
```
If you'd like to use "Distributed Configuration" features, `ConfigService` is a core service interface to get or publish config, you could use "Dependency Injection" to inject `ConfigService` instance in your Spring Beans.
```java
@Service
public class ConfigServiceDemo {
@NacosInjected
private ConfigService configService;
public void demoGetConfig() {
try {
String dataId = "{dataId}";
String group = "{group}";
String content = configService.getConfig(dataId, groupId, 5000);
System.out.println(content);
} catch (NacosException e) {
e.printStackTrace();
}
}
...
}
```
above code equals below one:
```java
try {
// Initialize the configuration service, and the console automatically obtains the following parameters through the sample code.
String serverAddr = "{serverAddr}";
String dataId = "{dataId}";
String group = "{group}";
Properties properties = new Properties();
properties.put("serverAddr", serverAddr);
ConfigService configService = NacosFactory.createConfigService(properties);
// Actively get the configuration.
String content = configService.getConfig(dataId, group, 5000);
System.out.println(content);
} catch (NacosException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
```
## Endpoint
Nacos config starter support the implementation of Spring Boot actuator endpoints.
**Prerequisite:**
Adding `nacos-config-spring-boot-actuator` to your pom.xml in Nacos Config Project.
Then Configure your endpoint security strategy.
* Spring Boot1.x
```properties
management.security.enabled=false
```
* Spring Boot2.x
```properties
management.endpoints.web.exposure.include=*
```
To view the endpoint information, visit the following URLS:
* Spring Boot1.x: URL is http://127.0.0.1:10011/nacos-config.
* Spring Boot2.x: URL is http://127.0.0.1:10011/actuator/nacos-config.
## Health Checks
`nacos-config-spring-boot-actuator` support the standard Spring Boot `HealthIndicator` as a production-ready feature , which will be aggregated into Spring Boot's `Health` and exported on `HealthEndpoint` that works MVC (Spring Web MVC) if it is available.
Suppose a Spring Boot Web application did not specify `management.server.port`(SpringBoot1.x using `management.port`), you can access http://localhost:{port}/actuator/health (SpringBoot1.x visit http://localhost:{port}/health) via Web Client and will get a response with JSON format is like below :
```json
{
"status": "UP",
"details": {
"nacosConfig": {
"status": "UP"
},
"diskSpace": {
"status": "UP",
"details": {
"total": 250140434432,
"free": 52323512320,
"threshold": 10485760
}
}
}
}
```
For more information about Nacos Spring, see [Nacos Spring Project](https://github.com/nacos-group/nacos-spring-project).
## Relative Projects
* [Alibaba Nacos](https://github.com/alibaba/nacos)
* [Alibaba Spring Context Support](https://github.com/alibaba/spring-context-support)
* [Nacos Spring Project](https://github.com/nacos-group/nacos-spring-project)
* [Nacos Spring Cloud Project](https://github.com/spring-cloud-incubator/spring-cloud-alibaba)

View File

@ -1,131 +0,0 @@
### Nacos Discovery
First, you have to start a Nacos Server in backend , If you don't know steps, you can learn about [quick start](https://nacos.io/en-us/docs/quick-start.html).
Suppose your Nacos Server is startup, you would add [`nacos-discovery-spring-boot-starter`](nacos-discovery-spring-boot-starter) in your Spring application's dependencies :
```xml
<dependencies>
...
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
<version>${latest.version}</version>
</dependency>
...
</dependencies>
```
Note: Version [0.2.x.RELEASE](https://mvnrepository.com/artifact/com.alibaba.boot/nacos-discovery-spring-boot-starter) is compatible with the Spring Boot 2.x. Version [0.1.x.RELEASE](https://mvnrepository.com/artifact/com.alibaba.boot/nacos-discovery-spring-boot-starter) is compatible with the Spring Boot 1.x.
After that, you could define some configurations in `application.properties`:
```properties
nacos.discovery.server-addr=localhost:8848
```
> `nacos.discovery.server-addr` attribute configures "\${host}:${port}" of your Nacos Server
Then you could using `@SpringBootApplication` to annotate main class like normal SpringBoot Application and startup:
```java
@SpringBootApplication
public class DiscoveryApplication {
public static void main(String[] args) {
SpringApplication.run(DiscoveryApplication.class, args);
}
}
```
If you'd like to use "Service Registry" features, `NamingService` is a core service interface to get or publish config, you could use "Dependency Injection" to inject `NamingService` instance in your Spring Beans.
```java
@Service
public class NamingServiceDemo {
@NacosInjected
private NamingService namingService;
public void demoRegisterService() {
try {
namingService.registerInstance("test-service", "1.1.1.1", 8080);
} catch (NacosException e) {
e.printStackTrace();
}
}
...
}
```
above code equals below one:
```java
try {
// Initialize the naming service, and the console automatically obtains the following parameters through the sample code.
String serverAddr = "{serverAddr}";
Properties properties = new Properties();
properties.put("serverAddr", serverAddr);
NamingService naming = NamingFactory.createNamingService(properties);
namingService.registerInstance("test-service", "1.1.1.1", 8080);
} catch (NacosException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
```
For more information about Nacos Spring, see [Nacos Spring Project](https://github.com/nacos-group/nacos-spring-project).
## Endpoint
Nacos discovery starter also support the implementation of Spring Boot actuator endpoints.
**Prerequisite:**
Adding `nacos-discovery-spring-boot-actuator` to your pom.xml in Nacos Discovery Project.
Then Configure your endpoint security strategy.
* Spring Boot1.x
```properties
management.security.enabled=false
```
* Spring Boot2.x
```properties
management.endpoints.web.exposure.include=*
```
To view the endpoint information, visit the following URLS:
* Spring Boot1.x: URL is http://127.0.0.1:10012/nacos-discovery.
* Spring Boot2.x: URL is http://127.0.0.1:10012/actuator/nacos-discovery.
## Health Checks
`nacos-discovery-spring-boot-actuator` support the standard Spring Boot `HealthIndicator` as a production-ready feature , which will be aggregated into Spring Boot's `Health` and exported on `HealthEndpoint` that works MVC (Spring Web MVC) if it is available.
Suppose a Spring Boot Web application did not specify `management.server.port`(SpringBoot1.x using `management.port`), you can access http://localhost:{port}/actuator/health (SpringBoot1.x visit http://localhost:{port}/health) via Web Client and will get a response with JSON format is like below :
```json
{
"status": "UP",
"details": {
"nacosDiscovery": {
"status": "UP"
},
"diskSpace": {
"status": "UP",
"details": {
"total": 250140434432,
"free": 52323680256,
"threshold": 10485760
}
}
}
}
```

244
README.md
View File

@ -32,8 +32,6 @@ Nacos Spring Boot Project consist of two parts: `nacos-config-spring-boot` and `
| -------------- | ------------- |
| Java | 1.8+ |
| Spring Boot | 2.0.3.RELEASE |
| Nacos-Spring-Context | 0.2.2-RC1 |
**1.x branch**
@ -41,16 +39,252 @@ Nacos Spring Boot Project consist of two parts: `nacos-config-spring-boot` and `
| -------------- | ------------- |
| Java | 1.7+ |
| Spring Boot | 1.4.1.RELEASE |
| Nacos-Spring-Context | 0.2.2-RC1 |
## Quick Start
### Nacos Config
- [Nacos Config Quick Start](https://github.com/nacos-group/nacos-spring-boot-project/blob/master/NACOS-CONFIG-QUICK-START.md)
First, you have to start a Nacos Server in backend , If you don't know steps, you can learn about [quick start](https://nacos.io/en-us/docs/quick-start.html).
- [Nacos Discovery Quick Start](https://github.com/nacos-group/nacos-spring-boot-project/blob/master/NACOS-DISCOVERY-QUICK-START.md)
Suppose your Nacos Server is startup, you would add [`nacos-config-spring-boot-starter`](nacos-config-spring-boot-starter) in your Spring application's dependencies :
```xml
<dependencies>
...
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>${latest.version}</version>
</dependency>
...
</dependencies>
```
After that, you could define some configurations in `application.properties`:
```properties
nacos.config.server-addr=localhost
```
> `nacos.config.server-addr` attribute configures "\${host}:${port}" of your Nacos Server
Then you could using `@SpringBootApplication` to annotate main class like normal SpringBoot Application and startup:
```java
@SpringBootApplication
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
```
If you'd like to use "Distributed Configuration" features, `ConfigService` is a core service interface to get or publish config, you could use "Dependency Injection" to inject `ConfigService` instance in your Spring Beans.
```java
@Service
public class ConfigServiceDemo {
@NacosInjected
private ConfigService configService;
public void demoGetConfig() {
try {
String dataId = "{dataId}";
String group = "{group}";
String content = configService.getConfig(dataId, groupId, 5000);
System.out.println(content);
} catch (NacosException e) {
e.printStackTrace();
}
}
...
}
```
above code equals below one:
```java
try {
// Initialize the configuration service, and the console automatically obtains the following parameters through the sample code.
String serverAddr = "{serverAddr}";
String dataId = "{dataId}";
String group = "{group}";
Properties properties = new Properties();
properties.put("serverAddr", serverAddr);
ConfigService configService = NacosFactory.createConfigService(properties);
// Actively get the configuration.
String content = configService.getConfig(dataId, group, 5000);
System.out.println(content);
} catch (NacosException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
```
### Nacos Discovery
First, you have to start a Nacos Server in backend , If you don't know steps, you can learn about [quick start](https://nacos.io/en-us/docs/quick-start.html).
Suppose your Nacos Server is startup, you would add [`nacos-discovery-spring-boot-starter`](nacos-discovery-spring-boot-starter) in your Spring application's dependencies :
```xml
<dependencies>
...
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
<version>${latest.version}</version>
</dependency>
...
</dependencies>
```
After that, you could define some configurations in `application.properties`:
```properties
nacos.discovery.server-addr=localhost
```
> `nacos.discovery.server-addr` attribute configures "\${host}:${port}" of your Nacos Server
Then you could using `@SpringBootApplication` to annotate main class like normal SpringBoot Application and startup:
```java
@SpringBootApplication
public class DiscoveryApplication {
public static void main(String[] args) {
SpringApplication.run(DiscoveryApplication.class, args);
}
}
```
If you'd like to use "Service Registry" features, `NamingService` is a core service interface to get or publish config, you could use "Dependency Injection" to inject `NamingService` instance in your Spring Beans.
```java
@Service
public class NamingServiceDemo {
@NacosInjected
private NamingService namingService;
public void demoRegisterService() {
try {
namingService.registerInstance("test-service", "1.1.1.1", 8080);
} catch (NacosException e) {
e.printStackTrace();
}
}
...
}
```
above code equals below one:
```java
try {
// Initialize the naming service, and the console automatically obtains the following parameters through the sample code.
String serverAddr = "{serverAddr}";
Properties properties = new Properties();
properties.put("serverAddr", serverAddr);
NamingService naming = NamingFactory.createNamingService(properties);
namingService.registerInstance("test-service", "1.1.1.1", 8080);
} catch (NacosException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
```
For more information about Nacos Spring, see [Nacos Spring Project](https://github.com/nacos-group/nacos-spring-project).
## Endpoint
Nacos config starter and Nacos discovery starter also support the implementation of Spring Boot actuator endpoints.
**Prerequisite:**
Adding `nacos-config-spring-boot-actuator` to your pom.xml in Nacos Config Project.
Adding `nacos-discovery-spring-boot-actuator` to your pom.xml in Nacos Discovery Project.
Then Configure your endpoint security strategy.
* Spring Boot1.x
```properties
management.security.enabled=false
```
* Spring Boot2.x
```properties
management.endpoints.web.exposure.include=*
```
To view the endpoint information, visit the following URLS:
Nacos Config Project :
* Spring Boot1.x: Nacos Config Endpoint URL is http://127.0.0.1:10011/nacos-config.
* Spring Boot2.x: Nacos Config Endpoint URL is http://127.0.0.1:10011/actuator/nacos-config.
Nacos Discovery Project:
* Spring Boot1.x: Nacos Discovery Endpoint URL is http://127.0.0.1:10012/nacos-discovery.
* Spring Boot2.x: Nacos Discovery Endpoint URL is http://127.0.0.1:10012/actuator/nacos-discovery.
## Health Checks
`nacos-config-spring-boot-actuator` and `nacos-discovery-spring-boot-actuator` support the standard Spring Boot `HealthIndicator` as a production-ready feature , which will be aggregated into Spring Boot's `Health` and exported on `HealthEndpoint` that works MVC (Spring Web MVC) if it is available.
Suppose a Spring Boot Web application did not specify `management.server.port`(SpringBoot1.x using `management.port`), you can access http://localhost:{port}/actuator/health (SpringBoot1.x visit http://localhost:{port}/health) via Web Client and will get a response with JSON format is like below :
Nacos Config Project:
```json
{
"status": "UP",
"details": {
"nacosConfig": {
"status": "UP"
},
"diskSpace": {
"status": "UP",
"details": {
"total": 250140434432,
"free": 52323512320,
"threshold": 10485760
}
}
}
}
```
Nacos Discovery Project:
```json
{
"status": "UP",
"details": {
"nacosDiscovery": {
"status": "UP"
},
"diskSpace": {
"status": "UP",
"details": {
"total": 250140434432,
"free": 52323680256,
"threshold": 10485760
}
}
}
}
```
For more information about Nacos Spring, see [Nacos Spring Project](https://github.com/nacos-group/nacos-spring-project).

View File

@ -18,7 +18,7 @@
<parent>
<artifactId>nacos-spring-boot-parent</artifactId>
<groupId>com.alibaba.boot</groupId>
<version>0.9.0</version>
<version>0.1.2</version>
<relativePath>../nacos-spring-boot-parent/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -16,13 +16,15 @@
*/
package com.alibaba.boot.nacos.actuate.autoconfigure;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.condition.ConditionalOnEnabledEndpoint;
import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.boot.nacos.actuate.endpoint.NacosConfigEndpoint;
import com.alibaba.boot.nacos.config.NacosConfigConstants;
/**
* Nacos Config {@link Endpoint} Auto-{@link Configuration}
@ -31,11 +33,12 @@ import com.alibaba.boot.nacos.actuate.endpoint.NacosConfigEndpoint;
* @see Endpoint
*/
@Configuration
@ConditionalOnClass(Endpoint.class)
public class NacosConfigEndpointAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnEnabledEndpoint
@ConditionalOnEnabledEndpoint(NacosConfigConstants.ENDPOINT_PREFIX)
public NacosConfigEndpoint nacosEndpoint() {
return new NacosConfigEndpoint();
}

View File

@ -16,8 +16,8 @@
*/
package com.alibaba.boot.nacos.actuate.autoconfigure;
import org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator;
import org.springframework.boot.actuate.autoconfigure.ConditionalOnEnabledHealthIndicator;
import org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;

View File

@ -26,8 +26,8 @@ import java.util.Properties;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
@ -48,8 +48,7 @@ import com.alibaba.nacos.spring.util.NacosUtils;
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
* @see Endpoint
*/
@Endpoint(id = NacosConfigConstants.ENDPOINT_PREFIX)
public class NacosConfigEndpoint
public class NacosConfigEndpoint extends AbstractEndpoint<Map<String, Object>>
implements ApplicationListener<NacosConfigMetadataEvent> {
@Autowired
@ -57,7 +56,11 @@ public class NacosConfigEndpoint
private Map<String, JSONObject> nacosConfigMetadataMap = new HashMap<>();
@ReadOperation
public NacosConfigEndpoint() {
super(NacosConfigConstants.ENDPOINT_PREFIX);
}
@Override
public Map<String, Object> invoke() {
Map<String, Object> result = new HashMap<>();

View File

@ -18,7 +18,7 @@
<parent>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-spring-boot-parent</artifactId>
<version>0.9.0</version>
<version>0.1.2</version>
<relativePath>../nacos-spring-boot-parent</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -25,7 +25,7 @@ import com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig;
*/
public interface NacosConfigConstants {
String ENDPOINT_PREFIX = "nacos-config";
String ENDPOINT_PREFIX = "nacos_config";
String ENABLED = EnableNacosConfig.CONFIG_PREFIX + "enabled";

View File

@ -24,14 +24,15 @@ import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.spring.core.env.NacosPropertySource;
import com.alibaba.nacos.spring.core.env.NacosPropertySourcePostProcessor;
import com.alibaba.nacos.spring.factory.CacheableEventPublishingNacosServiceFactory;
import com.alibaba.nacos.spring.util.NacosBeanUtils;
import com.alibaba.nacos.spring.util.config.NacosConfigLoader;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.util.StringUtils;
import java.util.Properties;
@ -41,9 +42,9 @@ import static com.alibaba.nacos.spring.util.NacosUtils.buildDefaultPropertySourc
* @author <a href="mailto:liaochunyhm@live.com">liaochuntao</a>
* @since
*/
public class NacosConfigApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
public class NacosConfigApplicationInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private final Logger logger = LoggerFactory.getLogger(NacosConfigApplicationContextInitializer.class);
private final Logger logger = LoggerFactory.getLogger(NacosConfigApplicationInitializer.class);
private ConfigurableEnvironment environment;
@ -61,6 +62,7 @@ public class NacosConfigApplicationContextInitializer implements ApplicationCont
if (!isEnable()) {
logger.info("[Nacos Config Boot] : The preload configuration is not enabled");
} else {
logger.info("[Nacos Config Boot] : The preload configuration is enabled");
nacosConfigProperties = NacosConfigPropertiesUtils.buildNacosConfigProperties(environment);
Properties globalProperties = buildGlobalNacosProperties();
MutablePropertySources mutablePropertySources = environment.getPropertySources();

View File

@ -18,6 +18,8 @@ package com.alibaba.boot.nacos.config.autoconfigure;
import static com.alibaba.nacos.spring.util.NacosBeanUtils.CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME;
import com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@ -26,7 +28,6 @@ import org.springframework.context.annotation.Configuration;
import com.alibaba.boot.nacos.config.NacosConfigConstants;
import com.alibaba.boot.nacos.config.properties.NacosConfigProperties;
import com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig;
import org.springframework.context.annotation.Import;
/**
@ -36,10 +37,10 @@ import org.springframework.context.annotation.Import;
*/
@ConditionalOnProperty(name = NacosConfigConstants.ENABLED, matchIfMissing = true)
@ConditionalOnMissingBean(name = CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME)
@EnableConfigurationProperties(value = NacosConfigProperties.class)
@ConditionalOnClass(name = "org.springframework.boot.context.properties.bind.Binder")
@Import(value = {NacosConfigBootBeanDefinitionRegistrar.class})
@EnableNacosConfig
@EnableConfigurationProperties(value = NacosConfigProperties.class)
@ConditionalOnClass(name = "org.springframework.boot.bind.RelaxedDataBinder")
@Import(value = {NacosConfigBootBeanDefinitionRegistrar.class})
public class NacosConfigAutoConfiguration {
}

View File

@ -17,6 +17,7 @@
package com.alibaba.boot.nacos.config.autoconfigure;
import com.alibaba.boot.nacos.config.binder.NacosBootConfigurationPropertiesBinder;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
@ -47,3 +48,4 @@ public class NacosConfigBootBeanDefinitionRegistrar implements ImportBeanDefinit
}
}

View File

@ -20,16 +20,15 @@ import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties;
import com.alibaba.nacos.spring.context.properties.config.NacosConfigurationPropertiesBinder;
import com.alibaba.nacos.spring.core.env.NacosPropertySource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.boot.bind.RelaxedDataBinder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.ResolvableType;
import java.lang.reflect.Method;
import java.util.Properties;
import static com.alibaba.nacos.spring.util.NacosUtils.toProperties;
/**
* @author <a href="mailto:liaochunyhm@live.com">liaochuntao</a>
@ -40,40 +39,21 @@ public class NacosBootConfigurationPropertiesBinder extends NacosConfigurationPr
private final Logger logger = LoggerFactory.getLogger(NacosBootConfigurationPropertiesBinder.class);
private ConfigurableApplicationContext context;
private ConfigurationBeanFactoryMetadata beanFactoryMetadata;
public NacosBootConfigurationPropertiesBinder(ConfigurableApplicationContext applicationContext) {
super(applicationContext);
this.context = applicationContext;
this.beanFactoryMetadata = applicationContext.getBean(
ConfigurationBeanFactoryMetadata.BEAN_NAME,
ConfigurationBeanFactoryMetadata.class);
}
@Override
protected void doBind(Object bean, String beanName, String dataId, String groupId,
NacosConfigurationProperties properties, String content, ConfigService configService) {
String name = "nacos-bootstrap-" + beanName;
String configType = properties.yaml() ? ConfigType.YAML.getType() : properties.type().getType();
NacosPropertySource propertySource = new NacosPropertySource(name, dataId, groupId, content, configType);
context.getEnvironment().getPropertySources().addLast(propertySource);
Binder binder = Binder.get(context.getEnvironment());
ResolvableType type = getBeanType(bean, beanName);
Bindable<?> target = Bindable.of(type).withExistingValue(bean);
binder.bind(properties.prefix(), target);
Properties prop = toProperties(dataId, groupId, content, configType);
RelaxedDataBinder binder = new RelaxedDataBinder(bean, properties.prefix());
binder.bind(new MutablePropertyValues(prop));
publishBoundEvent(bean, beanName, dataId, groupId, properties, content, configService);
publishMetadataEvent(bean, beanName, dataId, groupId, properties);
context.getEnvironment().getPropertySources().remove(name);
}
private ResolvableType getBeanType(Object bean, String beanName) {
Method factoryMethod = this.beanFactoryMetadata.findFactoryMethod(beanName);
if (factoryMethod != null) {
return ResolvableType.forMethodReturnType(factoryMethod);
}
return ResolvableType.forClass(bean.getClass());
}
}

View File

@ -18,20 +18,19 @@ package com.alibaba.boot.nacos.config.util;
import com.alibaba.boot.nacos.config.NacosConfigConstants;
import com.alibaba.boot.nacos.config.properties.NacosConfigProperties;
import com.alibaba.boot.nacos.config.util.editor.NacosCharSequenceEditor;
import com.alibaba.boot.nacos.config.util.editor.NacosCustomBooleanEditor;
import com.alibaba.boot.nacos.config.util.editor.NacosBooleanEditor;
import com.alibaba.boot.nacos.config.util.editor.NacosEnumEditor;
import com.alibaba.boot.nacos.config.util.editor.NacosStringEditor;
import com.alibaba.nacos.api.config.ConfigType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.boot.env.EnumerableCompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Collection;
@ -50,14 +49,14 @@ public class NacosConfigPropertiesUtils {
BeanWrapper wrapper = new BeanWrapperImpl(new NacosConfigProperties());
wrapper.setAutoGrowNestedPaths(true);
wrapper.setExtractOldValueForEditor(true);
wrapper.registerCustomEditor(String.class, new NacosCharSequenceEditor());
wrapper.registerCustomEditor(boolean.class, new NacosCustomBooleanEditor(true));
wrapper.registerCustomEditor(String.class, new NacosStringEditor());
wrapper.registerCustomEditor(boolean.class, new NacosBooleanEditor());
wrapper.registerCustomEditor(ConfigType.class, new NacosEnumEditor(ConfigType.class));
wrapper.registerCustomEditor(Collection.class, new CustomCollectionEditor(ArrayList.class));
PropertySource target = findApplicationConfig(environment);
wrapper.setPropertyValues(dataSource((Map<String, String>) target.getSource()));
wrapper.setPropertyValues(dataSource((Map<String, Object>) target.getSource()));
NacosConfigProperties nacosConfigProperties = (NacosConfigProperties) wrapper.getWrappedInstance();
logger.debug("nacosConfigProperties : {}", nacosConfigProperties);
logger.info("nacosConfigProperties : {}", nacosConfigProperties);
return nacosConfigProperties;
}
@ -65,19 +64,29 @@ public class NacosConfigPropertiesUtils {
PropertySource<Map<String, String>> target = null;
MutablePropertySources mutablePropertySources = environment.getPropertySources();
for (PropertySource tmp : mutablePropertySources) {
// Spring puts the information of the application.properties file into class{OriginTrackedMapPropertySource}.
if (tmp instanceof OriginTrackedMapPropertySource) {
target = tmp;
// Spring puts the information of the application.properties file into applicationConfigurationProperties.
if ("applicationConfigurationProperties".equals(tmp.getName())) {
ArrayList<Object> list = (ArrayList) tmp.getSource();
for (Object obj : list) {
if (obj instanceof EnumerableCompositePropertySource) {
EnumerableCompositePropertySource propertySource = (EnumerableCompositePropertySource) obj;
target = (PropertySource<Map<String, String>>) propertySource.getSource().iterator().next();
break;
}
}
}
if (target != null) {
break;
}
}
return target;
}
private static Map<String, String> dataSource(Map<String, String> source) {
private static Map<String, Object> dataSource(Map<String, Object> source) {
source.remove(NacosConfigConstants.NACOS_BOOTSTRAP);
String prefix = NacosConfigConstants.PREFIX + ".";
HashMap<String, String> targetConfigInfo = new HashMap<>(source.size());
for (Map.Entry<String, String> entry : source.entrySet()) {
HashMap<String, Object> targetConfigInfo = new HashMap<>(source.size());
for (Map.Entry<String, Object> entry : source.entrySet()) {
if (entry.getKey().startsWith(prefix)) {
String key = entry.getKey().replace(prefix, "");
if (key.contains("-")) {

View File

@ -0,0 +1,70 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.boot.nacos.config.util.editor;
import java.beans.PropertyEditorSupport;
/**
* @author <a href="mailto:liaochunyhm@live.com">liaochuntao</a>
* @since
*/
public class NacosBooleanEditor extends PropertyEditorSupport {
public NacosBooleanEditor() {
}
@Override
public String getJavaInitializationString() {
Object var1 = this.getValue();
return var1 != null ? var1.toString() : "null";
}
@Override
public String getAsText() {
Object var1 = this.getValue();
return var1 instanceof Boolean ? this.getValidName((Boolean)var1) : null;
}
@Override
public void setAsText(String var1) throws IllegalArgumentException {
if (var1 == null) {
this.setValue((Object)null);
} else if (this.isValidName(true, var1)) {
this.setValue(Boolean.TRUE);
} else {
if (!this.isValidName(false, var1)) {
throw new IllegalArgumentException(var1);
}
this.setValue(Boolean.FALSE);
}
}
@Override
public String[] getTags() {
return new String[]{this.getValidName(true), this.getValidName(false)};
}
private String getValidName(boolean var1) {
return var1 ? "True" : "False";
}
private boolean isValidName(boolean var1, String var2) {
return this.getValidName(var1).equalsIgnoreCase(var2);
}
}

View File

@ -1,45 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.boot.nacos.config.util.editor;
import java.beans.PropertyEditorSupport;
/**
* @author <a href="mailto:liaochunyhm@live.com">liaochuntao</a>
* @since
*/
public class NacosCharSequenceEditor extends PropertyEditorSupport {
@Override
public void setValue(Object value) {
if (value == null) {
super.setValue("");
}
if (value instanceof CharSequence) {
CharSequence sequence = (CharSequence) value;
super.setValue(sequence.toString());
} else {
super.setValue(value);
}
}
@Override
public String getAsText() {
Object value = getValue();
return String.valueOf(value);
}
}

View File

@ -1,108 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.boot.nacos.config.util.editor;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import java.beans.PropertyEditorSupport;
/**
* @author <a href="mailto:liaochunyhm@live.com">liaochuntao</a>
* @since
*/
public class NacosCustomBooleanEditor extends PropertyEditorSupport {
public static final String VALUE_TRUE = "true";
public static final String VALUE_FALSE = "false";
public static final String VALUE_ON = "on";
public static final String VALUE_OFF = "off";
public static final String VALUE_YES = "yes";
public static final String VALUE_NO = "no";
public static final String VALUE_1 = "1";
public static final String VALUE_0 = "0";
@Nullable
private final String trueString;
@Nullable
private final String falseString;
private final boolean allowEmpty;
public NacosCustomBooleanEditor(boolean allowEmpty) {
this(null, null, allowEmpty);
}
public NacosCustomBooleanEditor(@Nullable String trueString, @Nullable String falseString, boolean allowEmpty) {
this.trueString = trueString;
this.falseString = falseString;
this.allowEmpty = allowEmpty;
}
@Override
public void setValue(Object value) {
super.setValue(convert(String.valueOf(value)));
}
public Object convert(String text) throws IllegalArgumentException {
String input = (text != null ? text.trim() : null);
if (this.allowEmpty && !StringUtils.hasLength(input)) {
// Treat empty String as null value.
return null;
}
else if (this.trueString != null && this.trueString.equalsIgnoreCase(input)) {
return Boolean.TRUE;
}
else if (this.falseString != null && this.falseString.equalsIgnoreCase(input)) {
return Boolean.FALSE;
}
else if (this.trueString == null &&
(VALUE_TRUE.equalsIgnoreCase(input) || VALUE_ON.equalsIgnoreCase(input) ||
VALUE_YES.equalsIgnoreCase(input) || VALUE_1.equals(input))) {
return Boolean.TRUE;
}
else if (this.falseString == null &&
(VALUE_FALSE.equalsIgnoreCase(input) || VALUE_OFF.equalsIgnoreCase(input) ||
VALUE_NO.equalsIgnoreCase(input) || VALUE_0.equals(input))) {
return Boolean.FALSE;
}
else {
throw new IllegalArgumentException("Invalid boolean value [" + text + "]");
}
}
@Override
public String getAsText() {
String t = String.valueOf(getValue());
if (Boolean.TRUE.equals(Boolean.valueOf(t))) {
return (this.trueString != null ? this.trueString : VALUE_TRUE);
}
else if (Boolean.FALSE.equals(Boolean.valueOf(t))) {
return (this.falseString != null ? this.falseString : VALUE_FALSE);
}
else {
return "";
}
}
}

View File

@ -16,11 +16,9 @@
*/
package com.alibaba.boot.nacos.config.util.editor;
import com.alibaba.nacos.api.config.ConfigType;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Component;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyEditor;
@ -59,19 +57,20 @@ public class NacosEnumEditor implements PropertyEditor {
@Override
public void setValue(Object var1) {
if (var1 instanceof CharSequence) {
ConfigType bean = ConfigType.valueOf(String.valueOf(var1).toUpperCase());
if (var1 != null && !this.type.isInstance(var1)) {
throw new IllegalArgumentException("Unsupported value: " + var1);
} else {
Object var2;
PropertyChangeListener[] var3;
synchronized(this.listeners) {
label45: {
var2 = this.value;
this.value = bean;
if (bean == null) {
this.value = var1;
if (var1 == null) {
if (var2 != null) {
break label45;
}
} else if (!bean.equals(var2)) {
} else if (!var1.equals(var2)) {
break label45;
}
@ -86,7 +85,7 @@ public class NacosEnumEditor implements PropertyEditor {
var3 = (PropertyChangeListener[])this.listeners.toArray(new PropertyChangeListener[var5]);
}
PropertyChangeEvent var4 = new PropertyChangeEvent(this, (String)null, var2, bean);
PropertyChangeEvent var4 = new PropertyChangeEvent(this, (String)null, var2, var1);
PropertyChangeListener[] var10 = var3;
int var6 = var3.length;
@ -105,7 +104,7 @@ public class NacosEnumEditor implements PropertyEditor {
@Override
public void setAsText(String var1) {
this.setValue(var1 != null ? Enum.valueOf(this.type, var1) : null);
this.setValue(var1 != null ? Enum.valueOf(this.type, var1.toUpperCase()) : null);
}
@Override

View File

@ -0,0 +1,95 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.boot.nacos.config.util.editor;
import java.beans.PropertyEditorSupport;
/**
* @author <a href="mailto:liaochunyhm@live.com">liaochuntao</a>
* @since
*/
public class NacosStringEditor extends PropertyEditorSupport {
public NacosStringEditor() {
}
@Override
public String getJavaInitializationString() {
Object var1 = this.getValue();
if (var1 == null) {
return "null";
} else {
String var2 = var1.toString();
int var3 = var2.length();
StringBuilder var4 = new StringBuilder(var3 + 2);
var4.append('"');
for(int var5 = 0; var5 < var3; ++var5) {
char var6 = var2.charAt(var5);
String var7;
int var8;
switch(var6) {
case '\b':
var4.append("\\b");
continue;
case '\t':
var4.append("\\t");
continue;
case '\n':
var4.append("\\n");
continue;
case '\f':
var4.append("\\f");
continue;
case '\r':
var4.append("\\r");
continue;
case '"':
var4.append("\\\"");
continue;
case '\\':
var4.append("\\\\");
continue;
default:
if (var6 >= ' ' && var6 <= '~') {
var4.append(var6);
continue;
}
var4.append("\\u");
var7 = Integer.toHexString(var6);
var8 = var7.length();
}
while(var8 < 4) {
var4.append('0');
++var8;
}
var4.append(var7);
}
var4.append('"');
return var4.toString();
}
}
@Override
public void setAsText(String var1) {
this.setValue(var1);
}
}

View File

@ -1,4 +1,4 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.alibaba.boot.nacos.config.autoconfigure.NacosConfigAutoConfiguration
org.springframework.context.ApplicationContextInitializer=\
com.alibaba.boot.nacos.config.autoconfigure.NacosConfigApplicationContextInitializer
com.alibaba.boot.nacos.config.autoconfigure.NacosConfigApplicationInitializer

View File

@ -18,7 +18,7 @@
<parent>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-spring-boot-parent</artifactId>
<version>0.9.0</version>
<version>0.1.2</version>
<relativePath>../nacos-spring-boot-parent</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -18,7 +18,7 @@
<parent>
<artifactId>nacos-spring-boot-parent</artifactId>
<groupId>com.alibaba.boot</groupId>
<version>0.9.0</version>
<version>0.1.2</version>
<relativePath>../nacos-spring-boot-parent/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -16,12 +16,14 @@
*/
package com.alibaba.boot.nacos.discovery.actuate.autoconfigure;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.condition.ConditionalOnEnabledEndpoint;
import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.boot.nacos.discovery.NacosDiscoveryConstants;
import com.alibaba.boot.nacos.discovery.actuate.endpoint.NacosDiscoveryEndpoint;
/**
@ -31,11 +33,12 @@ import com.alibaba.boot.nacos.discovery.actuate.endpoint.NacosDiscoveryEndpoint;
* @see Endpoint
*/
@Configuration
@ConditionalOnClass(Endpoint.class)
public class NacosDiscoveryEndpointsAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnEnabledEndpoint
@ConditionalOnEnabledEndpoint(NacosDiscoveryConstants.ENDPOINT_PREFIX)
public NacosDiscoveryEndpoint nacosDiscoveryEndpoint() {
return new NacosDiscoveryEndpoint();
}

View File

@ -16,8 +16,8 @@
*/
package com.alibaba.boot.nacos.discovery.actuate.autoconfigure;
import org.springframework.boot.actuate.autoconfigure.endpoint.EndpointAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator;
import org.springframework.boot.actuate.autoconfigure.ConditionalOnEnabledHealthIndicator;
import org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;

View File

@ -23,8 +23,8 @@ import java.util.Map;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.context.ApplicationContext;
import com.alibaba.boot.nacos.common.PropertiesUtils;
@ -43,15 +43,18 @@ import com.alibaba.nacos.spring.util.NacosUtils;
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
* @see Endpoint
*/
@Endpoint(id = NacosDiscoveryConstants.ENDPOINT_PREFIX)
public class NacosDiscoveryEndpoint {
public class NacosDiscoveryEndpoint extends AbstractEndpoint<Map<String, Object>> {
@Autowired
private ApplicationContext applicationContext;
private static final Integer PAGE_SIZE = 100;
@ReadOperation
public NacosDiscoveryEndpoint() {
super(NacosDiscoveryConstants.ENDPOINT_PREFIX);
}
@Override
public Map<String, Object> invoke() {
Map<String, Object> result = new HashMap<>();
@ -59,7 +62,7 @@ public class NacosDiscoveryEndpoint {
PropertiesUtils.extractSafeProperties(applicationContext.getBean(
DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME, Properties.class)));
NacosServiceFactory nacosServiceFactory = CacheableEventPublishingNacosServiceFactory.getSingleton();
NacosServiceFactory nacosServiceFactory = CacheableEventPublishingNacosServiceFactory.getSingleton();;
JSONArray array = new JSONArray();
for (NamingService namingService : nacosServiceFactory.getNamingServices()) {

View File

@ -18,7 +18,7 @@
<parent>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-spring-boot-parent</artifactId>
<version>0.9.0</version>
<version>0.1.2</version>
<relativePath>../nacos-spring-boot-parent</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -25,7 +25,7 @@ import com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscover
*/
public interface NacosDiscoveryConstants {
String ENDPOINT_PREFIX = "nacos-discovery";
String ENDPOINT_PREFIX = "nacos_discovery";
String ENABLED = EnableNacosDiscovery.DISCOVERY_PREFIX + "enabled";

View File

@ -16,7 +16,7 @@
*/
package com.alibaba.boot.nacos.discovery.autoconfigure;
import static com.alibaba.nacos.spring.util.NacosBeanUtils.DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME;
import com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@ -26,7 +26,8 @@ import org.springframework.context.annotation.Configuration;
import com.alibaba.boot.nacos.discovery.NacosDiscoveryConstants;
import com.alibaba.boot.nacos.discovery.properties.NacosDiscoveryProperties;
import com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery;
import static com.alibaba.nacos.spring.util.NacosBeanUtils.DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME;
/**
* Nacos Discovery Auto {@link Configuration}
@ -37,7 +38,7 @@ import com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscover
@ConditionalOnMissingBean(name = DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME)
@EnableNacosDiscovery
@EnableConfigurationProperties(value = NacosDiscoveryProperties.class)
@ConditionalOnClass(name = "org.springframework.boot.context.properties.bind.Binder")
@ConditionalOnClass(name = "org.springframework.boot.bind.RelaxedDataBinder")
public class NacosDiscoveryAutoConfiguration {
}

View File

@ -18,7 +18,7 @@
<parent>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-spring-boot-parent</artifactId>
<version>0.9.0</version>
<version>0.1.2</version>
<relativePath>../nacos-spring-boot-parent</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -18,7 +18,7 @@
<parent>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-spring-boot-parent</artifactId>
<version>0.9.0</version>
<version>0.1.2</version>
<relativePath>../nacos-spring-boot-parent</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -16,6 +16,7 @@
package com.alibaba.boot.nacos.common;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
@ -29,11 +30,13 @@ public class PropertiesUtils {
public static Map<Object, Object> extractSafeProperties(Properties properties) {
Map<Object, Object> result = new HashMap<>();
properties.forEach((key, val) -> {
Enumeration enumeration = properties.propertyNames();
while (enumeration.hasMoreElements()) {
String key = enumeration.nextElement().toString();
if (!PropertyKeyConst.SECRET_KEY.equals(key)) {
result.put(key, val);
result.put(key, properties.get(key));
}
}
});
return result;
}

View File

@ -18,7 +18,7 @@
<parent>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-spring-boot-project</artifactId>
<version>0.9.0</version>
<version>0.1.2</version>
<relativePath>../pom.xml</relativePath>
</parent>
@ -30,12 +30,13 @@
<description>Nacos Spring Boot Parent</description>
<properties>
<java.version>1.8</java.version>
<java.source.version>1.8</java.source.version>
<java.target.version>1.8</java.target.version>
<java.version>1.7</java.version>
<java.source.version>1.7</java.source.version>
<java.target.version>1.7</java.target.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.0.3.RELEASE</spring-boot.version>
<spring-boot.version>1.4.1.RELEASE</spring-boot.version>
<nacos.version>0.1.0</nacos.version>
<nacos-spring-context.version>0.3.1</nacos-spring-context.version>
<!-- Build args -->
<argline>-server -Xms256m -Xmx512m -XX:PermSize=64m -XX:MaxPermSize=128m -Dfile.encoding=UTF-8
@ -57,6 +58,12 @@
<dependencyManagement>
<dependencies>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.2</version>
</dependency>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
@ -252,7 +259,7 @@
<configuration>
<rules>
<requireJavaVersion>
<version>[1.8,)</version>
<version>[1.7,)</version>
</requireJavaVersion>
<requireProperty>
<property>project.name</property>

View File

@ -20,7 +20,7 @@
<parent>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-spring-boot-samples</artifactId>
<version>0.9.0</version>
<version>0.1.2</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -45,6 +45,11 @@
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>

View File

@ -26,7 +26,7 @@ import java.util.Map;
* @author <a href="mailto:liaochunyhm@live.com">liaochuntao</a>
* @since
*/
@NacosConfigurationProperties(dataId = "apple", type = ConfigType.YAML)
@NacosConfigurationProperties(dataId = "apple", type = ConfigType.YAML, ignoreNestedProperties = true)
public class Apple {
private List<String> list;

View File

@ -20,8 +20,8 @@ import static org.springframework.core.env.StandardEnvironment.SYSTEM_ENVIRONMEN
import static org.springframework.core.env.StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME;
import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.spring.context.annotation.EnableNacos;
import com.alibaba.nacos.spring.context.annotation.config.EnableNacosConfig;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
@ -44,6 +44,8 @@ import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
@SpringBootApplication
@NacosPropertySources(value = {
@NacosPropertySource(dataId = "people", autoRefreshed = true),
@NacosPropertySource(
name = "custom",
dataId = ConfigApplication.DATA_ID,
@ -51,7 +53,7 @@ import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
before = SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME,
after = SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME
)
@NacosPropertySource(dataId = "people", autoRefreshed = true)
})
@EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "192.168.16.104:8848"))
public class ConfigApplication {
@ -80,13 +82,8 @@ public class ConfigApplication {
return new Foo();
}
@Bean
public Apple apple() {
return new Apple();
}
@NacosConfigListener(
dataId = "people",
dataId = DATA_ID,
timeout = 500
)
public void onChange(String newContent) throws Exception {
@ -94,6 +91,29 @@ public class ConfigApplication {
System.out.println("onChange : " + newContent);
}
public static class FirstCommandLineRunner implements CommandLineRunner {
@NacosInjected
private ConfigService configService;
@Override
public void run(String... args) throws Exception {
if (configService.publishConfig(DATA_ID, Constants.DEFAULT_GROUP, content)) {
Thread.sleep(200);
System.out.println("First runner success: " + configService
.getConfig(DATA_ID, Constants.DEFAULT_GROUP, 5000));
}
else {
System.out.println("First runner error: publish config error");
}
}
}
@Bean
public Apple apple() {
return new Apple();
}
@Configuration
@ConditionalOnProperty(prefix = "people", name = "enable", havingValue = "true")
protected static class People {
@ -106,23 +126,6 @@ public class ConfigApplication {
}
public static class FirstCommandLineRunner implements CommandLineRunner {
@NacosInjected
private ConfigService configService;
@Override
public void run(String... args) throws Exception {
if (configService.publishConfig(DATA_ID, Constants.DEFAULT_GROUP, content)) {
Thread.sleep(200);
System.out.println("First runner success: " + configService.getConfig(DATA_ID, Constants.DEFAULT_GROUP, 5000));
}
else {
System.out.println("First runner error: publish config error");
}
}
}
public static class SecondCommandLineRunner implements CommandLineRunner {
@NacosValue("${dept:unknown}")

View File

@ -22,12 +22,13 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author <a href="mailto:liaochunyhm@live.com">liaochuntao</a>
* @since
*/
@Controller
@RestController
public class TestController {
@NacosValue(value = "${people.enable:bbbbb}", autoRefreshed = true)
@ -43,7 +44,7 @@ public class TestController {
}
@GetMapping("/apple")
public Apple getApplr() {
public Apple getApple() {
return apple;
}

View File

@ -1,4 +1,3 @@
nacos.config.server-addr=192.168.16.104:8848
nacos.config.data-id=people
nacos.config.group=DEFAULT_GROUP
@ -19,5 +18,7 @@ nacos.config.ext-config[0].enable-remote-sync-config=true
server.port=10011
security.basic.enabled=false
management.security.enabled=false
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

View File

@ -20,7 +20,7 @@
<parent>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-spring-boot-samples</artifactId>
<version>0.9.0</version>
<version>0.1.2</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -45,6 +45,11 @@
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>

View File

@ -71,9 +71,9 @@ public class DiscoveryApplication {
public void run(String... args) throws Exception {
List<Instance> instanceList = namingService.getAllInstances("test-service");
System.out.println("found instance: " + instanceList.size());
instanceList.forEach(instance -> {
for(Instance instance : instanceList) {
System.out.println(instance);
});
}
}
}

View File

@ -2,5 +2,4 @@ nacos.discovery.server-addr=localhost:8848
server.port=10012
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
management.security.enabled=false

View File

@ -20,7 +20,7 @@
<parent>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-spring-boot-parent</artifactId>
<version>0.9.0</version>
<version>0.1.2</version>
<relativePath>../nacos-spring-boot-parent/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

12
pom.xml
View File

@ -14,7 +14,7 @@
</properties>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-spring-boot-project</artifactId>
<version>0.9.0</version>
<version>0.1.2</version>
<packaging>pom</packaging>
@ -54,15 +54,7 @@
</mailingLists>
<developers>
<developer>
<id>Jim</id>
<name>Jim Fang</name>
<email>fangjian0423@gmail.com</email>
<url>https://github.com/fangjian0423</url>
<roles>
<role>Developer</role>
</roles>
</developer>
</developers>
<profiles>