1
0
mirror of https://gitee.com/mirrors/Spring-Cloud-Alibaba.git synced 2021-06-26 13:25:11 +08:00

Merge pull request #1 from spring-cloud-incubator/master

Merge
This commit is contained in:
Neptune 2018-09-22 15:47:56 +08:00 committed by GitHub
commit 883b7cbcbf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
26 changed files with 237 additions and 234 deletions

View File

@ -18,7 +18,7 @@
<properties>
<sentinel.version>0.1.1</sentinel.version>
<oss.version>3.1.0</oss.version>
<nacos.version>0.2.0</nacos.version>
<nacos.version>0.2.1-RC1</nacos.version>
</properties>
<dependencyManagement>

View File

@ -21,7 +21,7 @@
2. 在应用的 /src/main/resources/bootstrap.properties 配置文件中配置 Nacos Config 地址
spring.cloud.nacos.config.server-addr=127.0.0.1:8080
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
3. 完成上述两步后,应用会从 Nacos Config 中获取相应的配置,并添加在 Spring Environment 的 PropertySources 中。这里我们使用 @Value 注解来将对应的配置注入到 SampleController 的 userName 和 age 字段,并添加 @RefreshScope 打开动态刷新功能
@ -51,7 +51,7 @@
3. 在命令行执行如下命令,向 Nacos Server 中添加一条配置。
curl -X POST "http://127.0.0.1:8080/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=user.id=1%0Auser.name=james%0Auser.age=17"
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=user.id=1%0Auser.name=james%0Auser.age=17"
**注:你也可以使用其他方式添加,遵循 HTTP API 规范即可,若您使用的 Nacos 版本自带控制台,建议直接使用控制台进行配置**
@ -89,7 +89,7 @@
#### 验证动态刷新
1. 执行如下命令,修改 Nacos Server 端的配置数据
curl -X POST "http://127.0.0.1:8080/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=user.id=1%0Auser.name=james%0Auser.age=18"
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=user.id=1%0Auser.name=james%0Auser.age=18"
2. 在浏览器地址栏输入 `http://127.0.0.1:18084/user`,并点击调转,可以看到应用从 Nacos Server 中获取了最新的数据age 变成了 18。
@ -112,7 +112,7 @@ Nacos Client 从 Nacos Server 端获取数据时,调用的是此接口 `Config
在 Nacos Config Starter 中dataId 的拼接格式如下
${prefix} - ${spring.active.profile} . ${content-type}
${prefix} - ${spring.active.profile} . ${file-extension}
* `prefix` 默认为 `spring.application.name` 的值,也可以通过配置项 `spring.cloud.nacos.config.prefix`来配置。
@ -120,7 +120,7 @@ Nacos Client 从 Nacos Server 端获取数据时,调用的是此接口 `Config
**注意,当 activeprofile 为空时,对应的连接符 `-` 也将不存在dataId 的拼接格式变成 `${prefix}`.`${context.type}`**
* `content-type` 为配置内容的数据格式,可以通过配置项 `spring.cloud.nacos.config.content-type`来配置。
* `file-extension` 为配置内容的数据格式,可以通过配置项 `spring.cloud.nacos.config.content-type`来配置。
目前只支持 `properties` 类型。
#### group
@ -168,7 +168,7 @@ Spring Boot 2.x 可以通过访问 http://127.0.0.1:18084/actuator/nacos-config
服务端地址|spring.cloud.nacos.config.server-addr||
DataId前缀|spring.cloud.nacos.config.prefix||spring.application.name
Group|spring.cloud.nacos.config.group|DEFAULT_GROUP|
dataID后缀及数据格式|spring.cloud.nacos.config.content-type|properties|目前只支持 properties
dataID后缀及数据格式|spring.cloud.nacos.config.file-extension|properties|目前只支持 properties
配置内容的编码方式|spring.cloud.nacos.config.encode|UTF-8|配置的编码
获取配置的超时时间|spring.cloud.nacos.config.timeout|3000|单位为 ms
配置的命名空间|spring.cloud.nacos.config.namespace||常用场景之一是不同环境的配置的区分隔离,例如开发测试环境和生产环境的资源隔离等。

View File

@ -21,7 +21,7 @@ Before we start the demo, let's learn how to connect Nacos Config to a Spring Cl
2. Add Nacos server address configurations to file /src/main/resources/bootstrap.properties
spring.cloud.nacos.config.server-addr=127.0.0.1:8080
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
3. After completing the above two steps, the application will get the externalized configuration from Nacos Server and put it in the Spring Environment's PropertySources.We use the @Value annotation to inject the corresponding configuration into the userName and age fields of the SampleController, and add @RefreshScope to turn on dynamic refresh .
@RefreshScope
@ -50,7 +50,7 @@ Before we start the demo, let's learn how to connect Nacos Config to a Spring Cl
3. Execute the following command to add a configuration to Nacos Server.
curl -X POST "http://127.0.0.1:8080/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=user.id=1%0Auser.name=james%0Auser.age=17"
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=user.id=1%0Auser.name=james%0Auser.age=17"
**Note: You can also add it in other ways. If you are using the Nacos version with its own console, it is recommended to configure it directly using the console.**
@ -89,7 +89,7 @@ Enter `http://127.0.0.1:18084/user` in the browser address bar and click Go to,
#### Dynamic Refresh
1. Run the following command to modify the configuration data on the Nacos Server side.
curl -X POST "http://127.0.0.1:8080/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=user.id=1%0Auser.name=james%0Auser.age=18"
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=user.id=1%0Auser.name=james%0Auser.age=18"
2. Enter `http://127.0.0.1:18084/user` in the browser address bar and click Go to,
We can see that the app got the latest data from Nacos Server and the age becomes 18.
@ -113,7 +113,7 @@ Nacos Client gets data from Nacos Server through this method. `ConfigService.get
In Nacos Config Starter, the splicing format of dataId is as follows
${prefix} - ${spring.active.profile} . ${content-type}
${prefix} - ${spring.active.profile} . ${file-extension}
* `prefix` default value is `spring.application.name` value, which can also be configured via the configuration item `spring.cloud.nacos.config.prefix`.
@ -121,7 +121,7 @@ In Nacos Config Starter, the splicing format of dataId is as follows
**Note: when the activeprofile is empty, the corresponding connector `-` will also not exist, and the splicing format of the dataId becomes `${prefix}`.`${context.type}`**
* `content-type` is the data format of the configuration content, which can be configured by the configuration item `spring.cloud.nacos.config.content-type`.
* `file-extension` is the data format of the configuration content, which can be configured by the configuration item `spring.cloud.nacos.config.content-type`.
Currently only the `properties` type is supported.
#### group
@ -172,7 +172,7 @@ Configuration item|key|default value|Description
server address|spring.cloud.nacos.config.server-addr||
DataId prefix|spring.cloud.nacos.config.prefix||spring.application.name
Group|spring.cloud.nacos.config.group|DEFAULT_GROUP|
dataID content type|spring.cloud.nacos.config.content-type|properties|currently only support properties
dataID suffix|spring.cloud.nacos.config.file-extension|properties|the suffix of nacos config dataId, also the file extension of config content.
encoding |spring.cloud.nacos.config.encode|UTF-8|Content encoding
timeout|spring.cloud.nacos.config.timeout|3000|Get the configuration timeout period,unit is ms
namespace|spring.cloud.nacos.config.namespace||One of the common scenarios is the separation of the configuration of different environments, such as the development of the test environment and the resource isolation of the production environment.

View File

@ -16,39 +16,39 @@ import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Component
class SampleRunner implements ApplicationRunner {
@Value("${user.name}")
String userName;
@Value("${user.name}")
String userName;
@Value("${user.age}")
int userAge;
@Value("${user.age}")
int userAge;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println(userName);
System.out.println(userAge);
}
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println(userName);
System.out.println(userAge);
}
}
@RestController
@RefreshScope
class SampleController {
@Value("${user.name}")
String userName;
@Value("${user.name}")
String userName;
@Value("${user.age}")
int age;
@Value("${user.age}")
int age;
@RequestMapping("/user")
public String simple() {
return "Hello Nacos Config!" + "Hello " + userName + " " + age + "!";
}
@RequestMapping("/user")
public String simple() {
return "Hello Nacos Config!" + "Hello " + userName + " " + age + "!";
}
}

View File

@ -1 +1 @@
spring.cloud.nacos.config.server-addr=127.0.0.1:8080
spring.cloud.nacos.config.server-addr=127.0.0.1:8848

View File

@ -20,22 +20,19 @@ import org.springframework.web.client.RestTemplate;
@EnableFeignClients
public class ConsumerApplication {
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
@FeignClient(name = "service-provider")
public interface EchoService {
@RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
String echo(@PathVariable("str") String str);
}
@FeignClient(name = "service-provider")
public interface EchoService {
@RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
String echo(@PathVariable("str") String str);
}
}

View File

@ -15,31 +15,32 @@ import org.springframework.web.client.RestTemplate;
@RestController
public class TestController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private EchoService echoService;
@Autowired
private RestTemplate restTemplate;
@Autowired
private EchoService echoService;
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private DiscoveryClient discoveryClient;
@RequestMapping(value = "/echo-rest/{str}", method = RequestMethod.GET)
public String rest(@PathVariable String str) {
return restTemplate.getForObject("http://service-provider/echo/" + str,
String.class);
}
@RequestMapping(value = "/echo-rest/{str}", method = RequestMethod.GET)
public String rest(@PathVariable String str) {
return restTemplate.getForObject("http://service-provider/echo/" + str, String.class);
}
@RequestMapping(value = "/echo-feign/{str}", method = RequestMethod.GET)
public String feign(@PathVariable String str) {
return echoService.echo(str);
}
@RequestMapping(value = "/echo-feign/{str}", method = RequestMethod.GET)
public String feign(@PathVariable String str) {
return echoService.echo(str);
}
@RequestMapping(value = "/services/{service}", method = RequestMethod.GET)
public Object client(@PathVariable String service) {
return discoveryClient.getInstances(service);
}
@RequestMapping(value="/services/{service}",method = RequestMethod.GET)
public Object client(@PathVariable String service){
return discoveryClient.getInstances(service);
}
@RequestMapping(value="/services",method = RequestMethod.GET)
public Object services(){
return discoveryClient.getServices();
}
@RequestMapping(value = "/services", method = RequestMethod.GET)
public Object services() {
return discoveryClient.getServices();
}
}

View File

@ -1,4 +1,4 @@
spring.application.name=service-consumer
server.port=18083
management.endpoints.web.exposure.include=*
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8080
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

View File

@ -1,4 +1,4 @@
server.port=18082
spring.application.name=service-provider
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8080
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
management.endpoints.web.exposure.include=*

View File

@ -21,7 +21,7 @@
2. 在应用的 /src/main/resources/application.properties 配置文件中配置 Nacos Server 地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8080
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
3. 使用 @EnableDiscoveryClient 注解开启服务注册与发现功能
@ -70,7 +70,7 @@
### 验证
#### 查询服务
在浏览器输入此地址 `http://127.0.0.1:8080/nacos/v1/ns/instances?serviceName=service-provider`,并点击跳转,可以看到服务节点已经成功注册到 Nacos Server。
在浏览器输入此地址 `http://127.0.0.1:8848/nacos/v1/ns/instances?serviceName=service-provider`,并点击跳转,可以看到服务节点已经成功注册到 Nacos Server。
![查询服务](https://cdn.nlark.com/lark/0/2018/png/54319/1536986288092-5cf96af9-9a26-466b-85f6-39ad1d92dfdc.png)

View File

@ -20,7 +20,7 @@ Before we start the demo, let's learn how to connect Nacos Config to a Spring Cl
2. Add Nacos server address configurations to file /src/main/resources/application.properties.
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8080
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
3. Use the @EnableDiscoveryClient annotation to turn on service registration and discovery.
@ -72,7 +72,7 @@ Before we start the demo, let's learn how to connect Nacos Config to a Spring Cl
#### Query Service
Enter `http://127.0.0.1:8080/nacos/v1/ns/instances?serviceName=service-provider` in the browser address bar and click Go to, we can see that the service node has been successfully registered to Nacos Server.
Enter `http://127.0.0.1:8848/nacos/v1/ns/instances?serviceName=service-provider` in the browser address bar and click Go to, we can see that the service node has been successfully registered to Nacos Server.
![查询服务](https://cdn.nlark.com/lark/0/2018/png/54319/1536986288092-5cf96af9-9a26-466b-85f6-39ad1d92dfdc.png)

View File

@ -49,9 +49,9 @@ public class NacosConfigProperties {
*/
private String prefix;
/**
* the content type of nacos config content.
* the suffix of nacos config dataId, also the file extension of config content.
*/
private String contentType = "properties";
private String fileExtension = "properties";
/**
* timeout for get config from nacos.
@ -59,7 +59,8 @@ public class NacosConfigProperties {
private int timeout = 3000;
/**
* endpoint for Nacos, the domain name of a service, through which the server address can be dynamically obtained.
* endpoint for Nacos, the domain name of a service, through which the server address
* can be dynamically obtained.
*/
private String endpoint;
@ -88,7 +89,7 @@ public class NacosConfigProperties {
*/
private String clusterName;
//todo sts support
// todo sts support
public String getServerAddr() {
return serverAddr;
@ -106,12 +107,12 @@ public class NacosConfigProperties {
this.prefix = prefix;
}
public String getContentType() {
return contentType;
public String getFileExtension() {
return fileExtension;
}
public void setContentType(String contentType) {
this.contentType = contentType;
public void setFileExtension(String fileExtension) {
this.fileExtension = fileExtension;
}
public String getGroup() {
@ -188,50 +189,52 @@ public class NacosConfigProperties {
@Override
public String toString() {
return "NacosConfigProperties{" +
"serverAddr='" + serverAddr + '\'' +
", encode='" + encode + '\'' +
", group='" + group + '\'' +
", prefix='" + prefix + '\'' +
", contentType='" + contentType + '\'' +
", timeout=" + timeout +
", endpoint='" + endpoint + '\'' +
", namespace='" + namespace + '\'' +
", accessKey='" + accessKey + '\'' +
", secretKey='" + secretKey + '\'' +
", contextPath='" + contextPath + '\'' +
", clusterName='" + clusterName + '\'' +
'}';
return "NacosConfigProperties{" + "serverAddr='" + serverAddr + '\''
+ ", encode='" + encode + '\'' + ", group='" + group + '\'' + ", prefix='"
+ prefix + '\'' + ", fileExtension='" + fileExtension + '\''
+ ", timeout=" + timeout + ", endpoint='" + endpoint + '\''
+ ", namespace='" + namespace + '\'' + ", accessKey='" + accessKey + '\''
+ ", secretKey='" + secretKey + '\'' + ", contextPath='" + contextPath
+ '\'' + ", clusterName='" + clusterName + '\'' + '}';
}
public void overrideFromEnv(Environment env){
public void overrideFromEnv(Environment env) {
if(StringUtils.isEmpty(this.getServerAddr())) {
this.setServerAddr(env.resolvePlaceholders("${spring.cloud.nacos.config.server-addr:}"));
if (StringUtils.isEmpty(this.getServerAddr())) {
this.setServerAddr(
env.resolvePlaceholders("${spring.cloud.nacos.config.server-addr:}"));
}
if(StringUtils.isEmpty(this.getEncode())) {
this.setEncode(env.resolvePlaceholders("${spring.cloud.nacos.config.encode:}"));
if (StringUtils.isEmpty(this.getEncode())) {
this.setEncode(
env.resolvePlaceholders("${spring.cloud.nacos.config.encode:}"));
}
if(StringUtils.isEmpty(this.getNamespace())) {
this.setNamespace(env.resolvePlaceholders("${spring.cloud.nacos.config.namespace:}"));
if (StringUtils.isEmpty(this.getNamespace())) {
this.setNamespace(
env.resolvePlaceholders("${spring.cloud.nacos.config.namespace:}"));
}
if(StringUtils.isEmpty(this.getAccessKey())) {
this.setAccessKey(env.resolvePlaceholders("${spring.cloud.nacos.config.access-key:}"));
if (StringUtils.isEmpty(this.getAccessKey())) {
this.setAccessKey(
env.resolvePlaceholders("${spring.cloud.nacos.config.access-key:}"));
}
if(StringUtils.isEmpty(this.getSecretKey())) {
this.setSecretKey(env.resolvePlaceholders("${spring.cloud.nacos.config.secret-key:}"));
if (StringUtils.isEmpty(this.getSecretKey())) {
this.setSecretKey(
env.resolvePlaceholders("${spring.cloud.nacos.config.secret-key:}"));
}
if(StringUtils.isEmpty(this.getContextPath())) {
this.setContextPath(env.resolvePlaceholders("${spring.cloud.nacos.config.context-path:}"));
if (StringUtils.isEmpty(this.getContextPath())) {
this.setContextPath(env
.resolvePlaceholders("${spring.cloud.nacos.config.context-path:}"));
}
if(StringUtils.isEmpty(this.getClusterName())) {
this.setClusterName(env.resolvePlaceholders("${spring.cloud.nacos.config.cluster-name:}"));
if (StringUtils.isEmpty(this.getClusterName())) {
this.setClusterName(env
.resolvePlaceholders("${spring.cloud.nacos.config.cluster-name:}"));
}
if(StringUtils.isEmpty(this.getEndpoint())) {
this.setEndpoint(env.resolvePlaceholders("${spring.cloud.nacos.config.endpoint:}"));
if (StringUtils.isEmpty(this.getEndpoint())) {
this.setEndpoint(
env.resolvePlaceholders("${spring.cloud.nacos.config.endpoint:}"));
}
if(StringUtils.isEmpty(this.getPrefix())) {
this.setPrefix(env.resolvePlaceholders("${spring.cloud.nacos.config.prefix:}"));
if (StringUtils.isEmpty(this.getPrefix())) {
this.setPrefix(
env.resolvePlaceholders("${spring.cloud.nacos.config.prefix:}"));
}
}
}

View File

@ -69,15 +69,15 @@ public class NacosPropertySourceBuilder {
* @param dataId Nacos dataId
* @param group Nacos group
*/
NacosPropertySource build(String dataId, String group, String contentType) {
Properties p = loadNacosData(dataId, group, contentType);
NacosPropertySource build(String dataId, String group, String fileExtension) {
Properties p = loadNacosData(dataId, group, fileExtension);
if (p == null) {
return null;
}
return new NacosPropertySource(dataId, propertiesToMap(p), new Date());
}
private Properties loadNacosData(String dataId, String group, String contentType) {
private Properties loadNacosData(String dataId, String group, String fileExtension) {
String data = null;
try {
data = configService.getConfig(dataId, group, timeout);

View File

@ -16,7 +16,6 @@
package org.springframework.cloud.alibaba.nacos.client;
import java.util.Properties;
import org.slf4j.Logger;
@ -81,14 +80,14 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
Properties properties = getPropertiesFromEnv(env);
try {
configService = NacosFactory.createConfigService(properties);
configService = NacosFactory.createConfigService(properties);
}
catch (NacosException e) {
// todo 为什么这里是 checkException什么时候会抛出什么时候需要关心
logger.error("create config service error, nacosConfigProperties:{}, ", properties, e);
logger.error("create config service error, nacosConfigProperties:{}, ",
properties, e);
return null;
}
beanFactory.registerSingleton("configService", configService);
if (null == configService) {
@ -97,7 +96,8 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
return null;
}
long timeout = nacosConfigProperties.getTimeout();
nacosPropertySourceBuilder = new NacosPropertySourceBuilder(configService, timeout);
nacosPropertySourceBuilder = new NacosPropertySourceBuilder(configService,
timeout);
String applicationName = env.getProperty("spring.application.name");
logger.info("Initialize spring.application.name '" + applicationName + "'.");
@ -108,32 +108,34 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
dataIdPrefix = applicationName;
}
String contentType = nacosConfigProperties.getContentType();
String fileExtension = nacosConfigProperties.getFileExtension();
CompositePropertySource composite = new CompositePropertySource(
NACOS_PROPERTY_SOURCE_NAME);
loadApplicationConfiguration(composite, env, nacosGroup, dataIdPrefix, contentType);
loadApplicationConfiguration(composite, env, nacosGroup, dataIdPrefix,
fileExtension);
return composite;
}
private void loadApplicationConfiguration(
CompositePropertySource compositePropertySource, Environment environment,
String nacosGroup, String dataIdPrefix, String contentType) {
loadNacosDataIfPresent(compositePropertySource, dataIdPrefix + DOT + contentType,
nacosGroup, contentType);
String nacosGroup, String dataIdPrefix, String fileExtension) {
loadNacosDataIfPresent(compositePropertySource,
dataIdPrefix + DOT + fileExtension, nacosGroup, fileExtension);
for (String profile : environment.getActiveProfiles()) {
String dataId = dataIdPrefix + SEP1 + profile + DOT + contentType;
String dataId = dataIdPrefix + SEP1 + profile + DOT + fileExtension;
loadNacosDataIfPresent(compositePropertySource, dataId, nacosGroup,
contentType);
fileExtension);
}
// todo multi profile active order and priority
}
private void loadNacosDataIfPresent(final CompositePropertySource composite,
final String dataId, final String group,String contentType) {
NacosPropertySource ps = nacosPropertySourceBuilder.build(dataId, group, contentType);
final String dataId, final String group, String fileExtension) {
NacosPropertySource ps = nacosPropertySourceBuilder.build(dataId, group,
fileExtension);
if (ps != null) {
composite.addFirstPropertySource(ps);
}

View File

@ -9,12 +9,12 @@
"name": "spring.cloud.nacos.config.prefix",
"type": "java.lang.String",
"defaultValue": "${spring.application.name}",
"description": "the prefix of dataId, nacos config data meta info. dataId = prefix + '-' + ${spring.active.profile} + `-` + ${spring.cloud.nacos.config.content-type}."
"description": "the prefix of dataId, nacos config data meta info. dataId = prefix + '-' + ${spring.active.profile} + `.` + ${spring.cloud.nacos.config.file-extension}."
},
{
"name": "spring.cloud.nacos.config.content-type",
"name": "spring.cloud.nacos.config.file-extension",
"type": "java.lang.String",
"defaultValue": "properties",
"description": "the content type of nacos config content, only support properties now."
"description": "the suffix of nacos config dataId, also the file extension of config content, only support properties now."
}
]}

View File

@ -4,4 +4,4 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.cloud.alibaba.nacos.NacosConfigAutoConfiguration,\
org.springframework.cloud.alibaba.nacos.endpoint.NacosConfigEndpointAutoConfiguration
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.cloud.alibaba.nacos..analyzer.NacosConnectionFailureAnalyzerdiagnostics
org.springframework.cloud.alibaba.nacos.diagnostics.analyzer.NacosConnectionFailureAnalyzer

View File

@ -72,7 +72,7 @@ public class NacosConfigAutoConfigurationTests {
}
NacosConfigProperties nacosConfigProperties = this.context.getBean(NacosConfigProperties.class);
assertThat(nacosConfigProperties.getContentType()).isEqualTo("properties");
assertThat(nacosConfigProperties.getFileExtension()).isEqualTo("properties");
assertThat(nacosConfigProperties.getPrefix()).isEqualTo("myapp");
}

View File

@ -21,12 +21,12 @@
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
<artifactId>spring-cloud-context</artifactId>
</dependency>
<dependency>
@ -57,12 +57,7 @@
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>

View File

@ -34,7 +34,8 @@ import com.alibaba.nacos.api.naming.pojo.ListView;
*/
public class NacosDiscoveryClient implements DiscoveryClient {
private static final Logger LOGGER = LoggerFactory.getLogger(NacosDiscoveryClient.class);
private static final Logger LOGGER = LoggerFactory
.getLogger(NacosDiscoveryClient.class);
public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client";
@Autowired
@ -49,7 +50,7 @@ public class NacosDiscoveryClient implements DiscoveryClient {
public List<ServiceInstance> getInstances(String serviceId) {
try {
NamingService namingService = nacosRegistration.getNacosNamingService();
List<Instance> instances = namingService.selectInstances(serviceId,true);
List<Instance> instances = namingService.selectInstances(serviceId, true);
return hostToServiceInstanceList(instances, serviceId);
}
catch (Exception e) {
@ -58,25 +59,26 @@ public class NacosDiscoveryClient implements DiscoveryClient {
}
}
private static ServiceInstance hostToServiceInstance(Instance instance, String serviceId) {
private static ServiceInstance hostToServiceInstance(Instance instance,
String serviceId) {
NacosServiceInstance nacosServiceInstance = new NacosServiceInstance();
nacosServiceInstance.setHost(instance.getIp());
nacosServiceInstance.setPort(instance.getPort());
nacosServiceInstance.setServiceId(serviceId);
Map<String, String> metadata = new HashMap<String, String>();
metadata.put("instanceId", instance.getInstanceId());
metadata.put("weight", instance.getWeight()+"");
metadata.put("healthy", instance.isHealthy()+"");
metadata.put("cluster", instance.getCluster()+"");
metadata.put("weight", instance.getWeight() + "");
metadata.put("healthy", instance.isHealthy() + "");
metadata.put("cluster", instance.getCluster() + "");
metadata.putAll(instance.getMetadata());
nacosServiceInstance.setMetadata(metadata);
return nacosServiceInstance;
}
private static List<ServiceInstance> hostToServiceInstanceList(List<Instance> instances,
String serviceId) {
private static List<ServiceInstance> hostToServiceInstanceList(
List<Instance> instances, String serviceId) {
List<ServiceInstance> result = new ArrayList<ServiceInstance>(instances.size());
for (Instance instance: instances) {
for (Instance instance : instances) {
result.add(hostToServiceInstance(instance, serviceId));
}
return result;
@ -87,9 +89,11 @@ public class NacosDiscoveryClient implements DiscoveryClient {
try {
NamingService namingService = nacosRegistration.getNacosNamingService();
ListView<String> services = namingService.getServicesOfServer(1, Integer.MAX_VALUE);
ListView<String> services = namingService.getServicesOfServer(1,
Integer.MAX_VALUE);
return services.getData();
}catch( Exception e){
}
catch (Exception e) {
LOGGER.error("get service name from nacos server fail,", e);
return Collections.emptyList();
}

View File

@ -16,7 +16,6 @@
package org.springframework.cloud.alibaba.nacos;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ -49,7 +48,8 @@ public class NacosDiscoveryProperties {
private String serverAddr;
/**
* the domain name of a service, through which the server address can be dynamically obtained.
* the domain name of a service, through which the server address can be dynamically
* obtained.
*/
private String endpoint;
@ -91,8 +91,8 @@ public class NacosDiscoveryProperties {
private boolean registerEnabled = true;
/**
* The ip address your want to register for your service instance, needn't to set it if
* the auto detect ip works well
* The ip address your want to register for your service instance, needn't to set it
* if the auto detect ip works well.
*/
private String ip;
@ -123,7 +123,6 @@ public class NacosDiscoveryProperties {
private String secretKey;
@Autowired
@JsonIgnore
private InetUtils inetUtils;
@PostConstruct
@ -190,10 +189,6 @@ public class NacosDiscoveryProperties {
this.logName = logName;
}
public InetUtils getInetUtils() {
return inetUtils;
}
public void setInetUtils(InetUtils inetUtils) {
this.inetUtils = inetUtils;
}
@ -296,47 +291,45 @@ public class NacosDiscoveryProperties {
@Override
public String toString() {
return "NacosDiscoveryProperties{" +
"serverAddr='" + serverAddr + '\'' +
", endpoint='" + endpoint + '\'' +
", namespace='" + namespace + '\'' +
", logName='" + logName + '\'' +
", service='" + service + '\'' +
", weight=" + weight +
", clusterName='" + clusterName + '\'' +
", metadata=" + metadata +
", registerEnabled=" + registerEnabled +
", ip='" + ip + '\'' +
", networkInterface='" + networkInterface + '\'' +
", port=" + port +
", secure=" + secure +
", accessKey='" + accessKey + '\'' +
", secretKey='" + secretKey + '\'' +
'}';
return "NacosDiscoveryProperties{" + "serverAddr='" + serverAddr + '\''
+ ", endpoint='" + endpoint + '\'' + ", namespace='" + namespace + '\''
+ ", logName='" + logName + '\'' + ", service='" + service + '\''
+ ", weight=" + weight + ", clusterName='" + clusterName + '\''
+ ", metadata=" + metadata + ", registerEnabled=" + registerEnabled
+ ", ip='" + ip + '\'' + ", networkInterface='" + networkInterface + '\''
+ ", port=" + port + ", secure=" + secure + ", accessKey='" + accessKey
+ '\'' + ", secretKey='" + secretKey + '\'' + '}';
}
public void overrideFromEnv(Environment env){
public void overrideFromEnv(Environment env) {
if(StringUtils.isEmpty(this.getServerAddr())) {
this.setServerAddr(env.resolvePlaceholders("${spring.cloud.nacos.discovery.server-addr:}"));
if (StringUtils.isEmpty(this.getServerAddr())) {
this.setServerAddr(env
.resolvePlaceholders("${spring.cloud.nacos.discovery.server-addr:}"));
}
if(StringUtils.isEmpty(this.getNamespace())) {
this.setNamespace(env.resolvePlaceholders("${spring.cloud.nacos.discovery.namespace:}"));
if (StringUtils.isEmpty(this.getNamespace())) {
this.setNamespace(env
.resolvePlaceholders("${spring.cloud.nacos.discovery.namespace:}"));
}
if(StringUtils.isEmpty(this.getAccessKey())) {
this.setAccessKey(env.resolvePlaceholders("${spring.cloud.nacos.discovery.access-key:}"));
if (StringUtils.isEmpty(this.getAccessKey())) {
this.setAccessKey(env
.resolvePlaceholders("${spring.cloud.nacos.discovery.access-key:}"));
}
if(StringUtils.isEmpty(this.getSecretKey())) {
this.setSecretKey(env.resolvePlaceholders("${spring.cloud.nacos.discovery.secret-key:}"));
if (StringUtils.isEmpty(this.getSecretKey())) {
this.setSecretKey(env
.resolvePlaceholders("${spring.cloud.nacos.discovery.secret-key:}"));
}
if(StringUtils.isEmpty(this.getLogName())) {
this.setLogName(env.resolvePlaceholders("${spring.cloud.nacos.discovery.log-name:}"));
if (StringUtils.isEmpty(this.getLogName())) {
this.setLogName(
env.resolvePlaceholders("${spring.cloud.nacos.discovery.log-name:}"));
}
if(StringUtils.isEmpty(this.getClusterName())) {
this.setClusterName(env.resolvePlaceholders("${spring.cloud.nacos.discovery.clusterName-name:}"));
if (StringUtils.isEmpty(this.getClusterName())) {
this.setClusterName(env.resolvePlaceholders(
"${spring.cloud.nacos.discovery.clusterName-name:}"));
}
if(StringUtils.isEmpty(this.getEndpoint())) {
this.setEndpoint(env.resolvePlaceholders("${spring.cloud.nacos.discovery.endpoint:}"));
if (StringUtils.isEmpty(this.getEndpoint())) {
this.setEndpoint(
env.resolvePlaceholders("${spring.cloud.nacos.discovery.endpoint:}"));
}
}

View File

@ -39,7 +39,8 @@ import org.springframework.cloud.alibaba.nacos.registry.NacosRegistration;
@Endpoint(id = "nacos-discovery")
public class NacosDiscoveryEndpoint {
private static final Logger LOGGER = LoggerFactory.getLogger(NacosDiscoveryEndpoint.class);
private static final Logger LOGGER = LoggerFactory
.getLogger(NacosDiscoveryEndpoint.class);
@Autowired
private NacosDiscoveryProperties nacosDiscoveryProperties;
@ -56,14 +57,15 @@ public class NacosDiscoveryEndpoint {
result.put("NacosDiscoveryProperties", nacosDiscoveryProperties);
NamingService namingService = nacosRegistration.getNacosNamingService();
List<ServiceInfo> subscribe = Collections.emptyList() ;
List<ServiceInfo> subscribe = Collections.emptyList();
try{
try {
subscribe = namingService.getSubscribeServices();
} catch (Exception e){
}
catch (Exception e) {
LOGGER.error("get subscribe services from nacos fail,", e);
}
result.put("subscribe",subscribe);
result.put("subscribe", subscribe);
return result;
}
}

View File

@ -20,19 +20,21 @@ import org.springframework.boot.actuate.autoconfigure.endpoint.condition.Conditi
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author xiaojing
*/
@ConditionalOnWebApplication
@Configuration
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
@ConditionalOnClass(Endpoint.class)
public class NacosDiscoveryEndpointAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnEnabledEndpoint
@Bean
public NacosDiscoveryEndpoint nacosDiscoveryEndpoint() {
return new NacosDiscoveryEndpoint();
}

View File

@ -16,7 +16,6 @@
package org.springframework.cloud.alibaba.nacos.registry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -29,16 +28,18 @@ import org.springframework.util.StringUtils;
/**
* @author xiaojing
*/
public class NacosAutoServiceRegistration extends AbstractAutoServiceRegistration<NacosRegistration> {
private static final Logger LOGGER = LoggerFactory.getLogger(NacosAutoServiceRegistration.class);
public class NacosAutoServiceRegistration
extends AbstractAutoServiceRegistration<NacosRegistration> {
private static final Logger LOGGER = LoggerFactory
.getLogger(NacosAutoServiceRegistration.class);
@Autowired
private NacosRegistration registration;
public NacosAutoServiceRegistration(ServiceRegistry<NacosRegistration> serviceRegistry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
NacosRegistration registration) {
public NacosAutoServiceRegistration(
ServiceRegistry<NacosRegistration> serviceRegistry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
NacosRegistration registration) {
super(serviceRegistry, autoServiceRegistrationProperties);
this.registration = registration;
}
@ -83,7 +84,6 @@ public class NacosAutoServiceRegistration extends AbstractAutoServiceRegistratio
}
@Override
protected Object getConfiguration() {
return this.registration.getNacosDiscoveryProperties();
@ -102,4 +102,3 @@ public class NacosAutoServiceRegistration extends AbstractAutoServiceRegistratio
}
}

View File

@ -34,6 +34,7 @@ import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.client.naming.utils.UtilAndComs;
import static com.alibaba.nacos.api.PropertyKeyConst.*;
/**
* @author xiaojing
*/
@ -54,11 +55,12 @@ public class NacosRegistration implements Registration, ServiceInstance {
Properties properties = new Properties();
properties.put(SERVER_ADDR, nacosDiscoveryProperties.getServerAddr());
properties.put(NAMESPACE, nacosDiscoveryProperties.getNamespace());
properties.put(UtilAndComs.NACOS_NAMING_LOG_NAME, nacosDiscoveryProperties.getLogName());
properties.put(UtilAndComs.NACOS_NAMING_LOG_NAME,
nacosDiscoveryProperties.getLogName());
properties.put(ENDPOINT, nacosDiscoveryProperties.getEndpoint());
properties.put(ACCESS_KEY,nacosDiscoveryProperties.getAccessKey());
properties.put(SECRET_KEY,nacosDiscoveryProperties.getSecretKey());
properties.put(CLUSTER_NAME,nacosDiscoveryProperties.getClusterName());
properties.put(ACCESS_KEY, nacosDiscoveryProperties.getAccessKey());
properties.put(SECRET_KEY, nacosDiscoveryProperties.getSecretKey());
properties.put(CLUSTER_NAME, nacosDiscoveryProperties.getClusterName());
try {
nacosNamingService = NacosFactory.createNamingService(properties);
}
@ -128,15 +130,14 @@ public class NacosRegistration implements Registration, ServiceInstance {
}
public void setNacosDiscoveryProperties(
NacosDiscoveryProperties nacosDiscoveryProperties) {
NacosDiscoveryProperties nacosDiscoveryProperties) {
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
}
@Override
public String toString() {
return "NacosRegistration{" +
"nacosDiscoveryProperties=" + nacosDiscoveryProperties +
", nacosNamingService=" + nacosNamingService +
'}';
return "NacosRegistration{" + "nacosDiscoveryProperties="
+ nacosDiscoveryProperties + ", nacosNamingService=" + nacosNamingService
+ '}';
}
}

View File

@ -31,13 +31,13 @@ public class NacosServer extends Server {
private final Instance instance;
private final Map<String, String> metadata;
public NacosServer(Instance instance) {
public NacosServer(final Instance instance) {
super(instance.getIp(), instance.getPort());
this.instance = instance;
this.metaInfo = new MetaInfo() {
@Override
public String getAppName() {
return instance.getService().getName();
return instance.serviceName();
}
@Override

View File

@ -36,7 +36,8 @@ public class NacosServerList extends AbstractServerList<NacosServer> {
private String serviceId;
public NacosServerList(){}
public NacosServerList() {
}
public NacosServerList(String serviceId) {
this.serviceId = serviceId;
@ -54,11 +55,14 @@ public class NacosServerList extends AbstractServerList<NacosServer> {
private List<NacosServer> getServers() {
try {
List<Instance> instances = registration.getNacosNamingService().selectInstances(serviceId, true);
List<Instance> instances = registration.getNacosNamingService()
.getAllInstances(serviceId);
return instancesToServerList(instances);
}
catch (Exception e) {
throw new IllegalStateException("Can not get service instances from nacos, serviceId=" + serviceId, e);
throw new IllegalStateException(
"Can not get service instances from nacos, serviceId=" + serviceId,
e);
}
}